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() ^~~~~