S Wang
S Wang

Reputation: 223

C++ Const Member Function (Beginner)

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

Answers (1)

robor
robor

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();
}
  1. s is a pointer to a constant. Calling a non const method causes

passing ‘const TestClass’ as ‘this’ argument discards qualifiers [-fpermissive]

  1. However s can point to a different instance. As said in the comments the pointer can be pointed to a different variable.

Upvotes: 3

Related Questions