'this' is of type "Class * const", although the method is not a constant

Today I noticed something strange regarding the type of 'this'. If you have something like this:

class C { void funcA() { funcB(this); } void funcB(C obj) { //do something } }; 

You will, of course, get an error, because funcB () expects an object, and 'this' is a pointer. I accidentally forgot an asterisk, but was surprised by the error message as it said:

 no matching function for call to 'C::funcB(C* const)' 

Where does the constant come from when funcA () is not a constant?

+4
source share
5 answers

Saying that this pointer itself is like const - that is, you cannot change the pointer to point to another memory.

In the earliest history of C ++, before you could overload new and delete , or create a new invention, this was a non-constant pointer (at least inside ctor). The class that wanted to handle its own memory management did this by allocating space for the instance in the constructor and writing the address of that memory into this before exiting the constructor.

In a constant member function, the type you would be dealing with would be Class const *const this , which means that this points to const (as well as the const pointer itself).

+9
source

C* const does not mean that an object of type C is constant. It will be C const* or const C* .

C* const means that the pointer itself is constant.

Which makes sense as you cannot do

 this = &something_else; 
+8
source

Note that this is not C const * , but C* const . That is (reading from right to left) a constant pointer to C

+4
source

There is a difference between C const* and C * const . You need to understand the difference:

  • C const* means that it is a constant object (indicated by a pointer).
  • C * const means that it is a constant pointer.

So, this by definition is a pointer of type C * const , so it cannot be changed, although the object it points to can still be changed.

+4
source

The pointer itself is constant, not the specified data.

+3
source

All Articles