I was re-reading c++ primer(4th ed.) today – the section on member functions and const references etc, and I came up with this wierd little program:
using std::cout;
using std::endl;
class ConstCheater
{
public:
ConstCheater(int avalue) : ccp(this), value(avalue) {}
ConstCheater& getccp() const {return *ccp;}
int value;
private:
ConstCheater* ccp;
};
int main()
{
const ConstCheater cc(7); //Initialize the value to 7
cout << cc.value << endl;
cc.getccp().value = 4; //Now setting it to 4, even though it's const!
cout << cc.value << endl;
cc.value = 4; //This is illegal
return 0;
}
My question is – why does c++ allow syntax such as this? Why can I edit normal data members in a class when it’s declared const? Isn’t the POINT of const to make it so that you can’t modify values?
I’d say the answer by Tony that you marked as correct is incorrect, and the answer by Michael Burr is correct.
To put what he said more clearly (for me at least):
There are two potential places for misunderstanding:
thisis interpreted during construction of a const object1. Implicit Const
Implicit const (the constification internal to
ConstCheaterwhen it is madeconst) doesn’t turnccinto apointer-to-constbut rather aconst-pointer, that is to say when you do this:Internally goes from:
…to…
…rather than the…
that may have been expected.
2. Construction of
constobjectThe stranger thing is though is that
thisis allowed to be passed tocpp‘s initializer in the constructor sincethis, one would think, should be treated as apointer-to-const, and thus not a valid value to pass to aconst-pointer.That is to say one might expect:
to fail because conceptually you might expect that this was (somewhat) equivalent to:
and thus you would think that:
would fail! But it doesn’t because apparently during construction apparently
thisis treated specially as if it was:and thus the object is effectively not const during construction.
I’m not sure I understand completely the reasoning, but Michael Burr points out there appears to be a logical and technical barrier to providing the expected behavior so the standard seems to carve out the current somewhat odd behavior.
I recently asked a related question which was: Why does C++ not have a const constructor? but thus far haven’t really understood completely the reasoning why it would be untenable, though I suppose it would place a burden on C++ developers to have to define an awkward const constructor for any class they’d like to create const object of.