about const member function
-
class Text { public: void bad( const string &parm ) const; private: char *_text; }; void Text::bad( const string &parm ) const { _text = parm.c_str(); // error: _text cannot be modified for ( int ix = 0; ix < parm.size(); ++ix ) _text[ix] = parm[ix]; // bad style but not an error } this example show a pointer refer change a data member in the const member function , why?
-
class Text { public: void bad( const string &parm ) const; private: char *_text; }; void Text::bad( const string &parm ) const { _text = parm.c_str(); // error: _text cannot be modified for ( int ix = 0; ix < parm.size(); ++ix ) _text[ix] = parm[ix]; // bad style but not an error } this example show a pointer refer change a data member in the const member function , why?
-
class Text { public: void bad( const string &parm ) const; private: char *_text; }; void Text::bad( const string &parm ) const { _text = parm.c_str(); // error: _text cannot be modified for ( int ix = 0; ix < parm.size(); ++ix ) _text[ix] = parm[ix]; // bad style but not an error } this example show a pointer refer change a data member in the const member function , why?
_text is a char*. The const member promises not to change any of the member variables. Your first assignment changes _text to point to a different string. The second assignment (in the loop) does not change _text, but the content of the string that _text points to (btw, I assume that _text has been assigned to a valid string at some point in code not shown, otherwise the second assignment will corrupt your memory). const pointers can point to mutable objects. You may change content of the object, but not the content of the pointer.
Cheers Steen. "Are you gonna check your makeup when you're done whining?" John Simmons, 05/31/2006 "Of course, the next day it automatically updates, and your quick'n'dirty patches cause the new binaries to segfault all over your linoleum. If only you'd had the source..." Shog, 10/18/2006 "One day I realized that sadness is just another word for not enough coffee" Wally, 10/18/2006