Search code examples
c++constants

Unable to use the 'this' pointer in a const member function


I was going through: C++ FAQs about inheritance and decided to implement it just to learn it:

#include "Shape.h"
 
 void Shape::print() const
 {
     float a = this->area();  // area() is pure virtual
     ...
 } 

Now, everything (well, almost) works as described in the FAQ except that print() is const and so it can't access the this pointer. As soon as you take out const, it works.

The C++ FAQ has been around for a while and is usually pretty good. Is this a mistake? Does it have a typo or am I wrong? If I'm wrong, I would like to know how is it possible to access the this pointer in a const function.


Solution

  • The problem is that the area() function is not const. If that function was const, then this would compile fine. Since your inside a const function, the this pointer is const and therefore you can only call const functions on it.