Note that there are some explanatory texts on larger screens.

plurals
  1. PODo non const internal members of class become const when I have const ref to an object of that class?
    primarykey
    data
    text
    <p>Well, I think my problem originates in a lake of knowledge of basic C++ concepts. The problem is, in my code (below) I have the classes Header and Register. For both, I pass a reference to a ifstrem file already opened. The Header reads some bytes from it. Register has a method to return a reference of Header (which is passed in Register constructor). </p> <p>The problem is, when I declare the reference to Header as const (in my Register class), I've got an error message saying:</p> <pre><code>error C2662: 'Header::Field_1' : cannot convert 'this' pointer from 'const Header' to 'Header &amp;' </code></pre> <p>The problem, I guess, is:</p> <p>Field_1 method changes the file cursor through seekg. therefore this member object cannot be const (its internal structure is being changed). Being fstream _stream declared inside Header class, and having a const reference for this class does it make all its internal members const as well?</p> <p>PS: I'm using VS C++ express. The code below doesn't do anything useful, is just an example.</p> <pre><code>// ********** HEADER.H *********** #ifndef __HEADER_H__ #define __HEADER_H__ #include &lt;fstream&gt; class Header { private: std::ifstream* _stream; unsigned long field1; public: Header(std::ifstream* stream); ~Header() { } unsigned long Field_1(void); }; class Register { private: const Header&amp; _header; std::ifstream* _stream; public: Register(const Header&amp; header, std::ifstream* stream); ~Register(){ } const Header&amp; GetHeader(void) { return _header; } }; #endif /*__HEADER_H__*/ //********* PROGRAM.CPP ************* #include &lt;iostream&gt; #include "header.h" using namespace std; Header::Header(ifstream* stream) : _stream(stream) { } unsigned long Header::Field_1(void) { _stream-&gt;seekg(0x00, fstream::beg); _stream-&gt;read(reinterpret_cast&lt;char*&gt;(&amp;field1), sizeof(field1)); return field1; } Register::Register(const Header&amp; header, std::ifstream* stream): _header(header), _stream(stream) { } int main(void) { ifstream file("test.dat", ios::binary | ios::in); Header h(&amp;file); Register reg(h, &amp;file); cout &lt;&lt; "Field 1 " &lt;&lt; reg.GetHeader().Field_1() &lt;&lt; endl; file.close(); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload