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?
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
).
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With