Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' of type "Class* const" even though method is not const

Tags:

c++

constants

Today I noticed something strange about 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, while 'this' is a pointer. I accidentally did forget the asterisk, but was surprised by the error message, as it said:

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

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

like image 562
x squared Avatar asked Nov 27 '22 14:11

x squared


2 Answers

That's saying that the this pointer itself as const -- i.e., you can't modify the pointer to point to different memory.

Back in the very early history of C++, before you could overload new and delete, or placement new was invented, this was a non-const pointer (at least inside the ctor). A class that wanted to handle its own memory management did so by allocating space for an instance in the constructor, and writing the address of that memory into this before exiting the constructor.

In a const member function the type you'd be dealing would be Class const *const this, meaning that what this points at is const (as well as the pointer itself being const).

like image 53
Jerry Coffin Avatar answered Dec 18 '22 07:12

Jerry Coffin


C* const does not mean that the object of type C is constant. That would be C const* or const C*.

C* const means that the pointer itself is constant.

Which makes sense, since you cannot do

this = &something_else;
like image 20
aschepler Avatar answered Dec 18 '22 08:12

aschepler