How does member-function understand that the object is obtained by dereferencing a const pointer?

Viewed 181

I created a const pointer which points to an instance of abject allocated dynamically.I could not understand the object itself is const or not.

Firstly I tried to call a non-const member function by using pointer, as expected it caused a compile error because (it is my explanation, don't know if it is true or not) this pointer created by the member function is assigned to that const pointer. It did not yield anything.

Secondly I tried to dereference the pointer and call that non-const member function. I thought that the this pointer created by member function now will not be a const pointer because compile can not know the object returned by p (namely *p) is returned by a const pointer or not. It turns out that I was mistaken.

How does member-function understand that ?

#include<iostream>

class A
{
    int a=4;
public:
    A()
    {}

 void   print()
    {
        std::cout<<a<<std::endl;
    }
};


int main()
{
    const A* p = new A();  

   p->print(); //1 causes compile error
   (*p).print(); //2 causes compile error


  return 0;
}

I thought the line labelled as 2 will not create a compile error. It causes a compile error.The error message is:

"a.cpp: In function ‘int main()’:
a.cpp:21:13: error: passing ‘const A’ as ‘this’ argument discards qualifiers [-fpermissive]
    p->print(); //1 causes compile error
             ^
a.cpp:10:9: note:   in call to ‘void A::print()’
  void   print()
         ^~~~~
a.cpp:22:15: error: passing ‘const A’ as ‘this’ argument discards qualifiers [-fpermissive]
    (*p).print(); //2 causes compile error
               ^
a.cpp:10:9: note:   in call to ‘void A::print()’
  void   print()
         ^~~~~

3 Answers

Variables have types and can therefore be const or non-const, but expressions have types too. The type of (*p) is const A, and you can't call a non-const method of a const type.

There is no difference between (1) and (2). (1) is syntax sugar for (2). You should define the print method as const in order to call it for const object.

void print() const { ... }

As it has already been noted, expressions have types and the type of (*p) is const A. You cannot call a non-const function on an object of a const type but you can call const member function. Member functions can have a const qualifier which will mark them to be able to be invoked on const objects or pointers to const objects.

void print() const
{
   std::cout<<a<<std::endl;
}

This will make your code compile. and it looks like this is what you intended to do anyway.

Related