Search code examples
c++this-pointer

'this' in C++ is a pointer to a reference?


I know this is silly and the title probably isn't the answer.. I always thought of this as a pointer to the current object which is supplied in every method call from an object (which is not a static method)

but looking at what my code actually returns for example:

Test& Test::func () 
{ 
   // Some processing 
   return *this; 
} 

the dereference of this is returned... and the return type is a reference to the object.... so what does that make this? Is there something under the hood I'm not understanding well?


Solution

  • Remember that a reference is simply a different name for an object.

    That implies that returning a reference is the same thing as returning an object on type level of abstraction; it is not the same thing in the result: returning a reference means the caller gets a reference to the current object, whereas returning an object gives him (a reference to) a copy of the current object - with all the consequences, like the copy constructor being called, deep copy decisions are being made, etc.