Reputation: 223
In C++ Primer P259, it says
Objects that are const, and references or pointers to const objects, may call only const member functions.
Based on my current understanding, however, pointers to const objects not necessarily applies because the pointer itself is nonconst. As long as the member function does not modify the object being pointed to, it's legal to call nonconst member functions on pointers to const objects.
Is it correct?
Edit: OK I get it now, it is because when we "call member function on the pointer", we are actually dereferencing it first, and use the object underneath.
Upvotes: 1
Views: 185
Reputation: 3089
The quote is correct.
Try this
class TestClass
{
public:
void nonconst(){};
void constMethod() const {}
};
int main()
{
TestClass const *s = new TestClass();
//s->nonconst(); // (1) no not legal
s->constMethod();
s = new TestClass(); // (2) yes legal
s->constMethod();
}
passing ‘const TestClass’ as ‘this’ argument discards qualifiers [-fpermissive]
Upvotes: 3