crommy
crommy

Reputation: 493

'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?

Upvotes: 0

Views: 452

Answers (3)

avish
avish

Reputation: 48

To put it simply:

test t1;  //  t1 is a test object.

test& t2 = t1; //  t2 is another name for t1.

test* t3; //  t3 holds an address of a test object.

*t3; //  derefernce t. which gives you, the test object that t3 points to.

this is a pointer to the current test object.
therefore *this is the current test object, and because the return value type is test&, when you call the function, you get the same object you called the function from.

Upvotes: 1

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123440

From cppreference:

The keyword this is a prvalue expression whose value is the address of the object, on which the member function is being called.

And then (perhaps easier to grasp):

The type of this in a member function of class X is X* (pointer to X). If the member function is cv-qualified, the type of this is cv X* (pointer to identically cv-qualified X). Since constructors and destructors cannot be cv-qualified, the type of this in them is always X*, even when constructing or destroying a const object.

So, this is not a pointer to a reference, but just a pointer.

Actually you cannot have a pointer to a reference, because taking the address of a reference will give you the address of referenced object.

Further, there is no special syntax in C++ to form a reference. Instead references have to be bound on initialization, for example:

int x = 3;
int& y = x;   // x is int, but y is int&
assert( &y == &x); // address of y is the address of x

Similar when returning a reference from a function:

int& get_x() {
    static int x = 3;
    return x;
}

Upvotes: 1

Aganju
Aganju

Reputation: 6405

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.

Upvotes: 3

Related Questions