Search code examples
c++classoperator-overloadingthisassignment-operator

Why do we return *this in asignment operator and generally (and not &this) when we want to return a reference to the object?


I'm learning C++ and pointers and I thought I understood pointers until I saw this.

On one side the asterix(*) operator is dereferecing, which means it returns the value in the address the value is pointing to, and that the ampersand (&) operator is the opposite, and returns the address of where the value is stored in memory.

Reading now about assignment overloading, it says "we return *this because we want to return a reference to the object". Though from what I read *this actually returns the value of this, and actually &this logically should be returned if we want to return a reference to the object.

How does this add up? I guess I'm missing something here because I didn't find this question asked elsewhere, but the explanation seems like the complete opposite of what should be, regarding the logic of * to dereference, & get a reference.

For example here:

struct A {
  A& operator=(const A&) {
    cout << "A::operator=(const A&)" << endl;
    return *this;
  }
};

Solution

  • this is a pointer that keeps the address of the current object. So dereferencing the pointer like *this you will get the lvalue of the current object itself. And the return type of the copy assignment operator of the presented class is A&. So returning the expression *this you are returning a reference to the current object.

    According to the C++ 17 Standard (8.1.2 This)

    1 The keyword this names a pointer to the object for which a non-static member function (12.2.2.1) is invoked or a non-static data member’s initializer (12.2) is evaluated.

    Consider the following code snippet as an simplified example.

    int x = 10;
    
    int *this_x = &x;
    

    Now to return a reference to the object you need to use the expression *this_x as for example

    std::cout << *this_x << '\n';