Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
556 views
Welcome To Ask or Share your Answers For Others

1 Answer

Even though getccp() is a const method it makes no promises what you do with the reference it returns. The method itself does not modify the object and therefore does not break the rules.

If it returned a const ConstCheater& then that would be different.

As your example shows, there is much more complexity to const than just applying it to an object. the C++ FAQ has a section on const correctness and in particular it covers the case you are highlighting here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...