Search code examples
c++assignment-operatorcopy-assignment

Why does operator = return *this?


Say I want to override the operator = so I can do something like

Poly p1;  // an object representing a polynomial
Poly p2;  // another object of the same type    
p2 = p1;  // assigns all the contents of p1 to p2

Then in my implementation of the operator =, I have something like this:

Poly& Poly::operator=(const Poly &source) {
    // Skipping implementation, it already works fine…
    return *this;
}

Don't mind the implementation, it already works fine.

My concern is that what happens when you return *this? I know it returns a reference to the object but is this what happens?

p2 = &p1

Solution

  • You return *this so you can write normal compound C++ = statements like:

    Poly p1; //an object representing a polynomial
    Poly p2;
    Poly p2;
    
    // ...
    
    p3 = p2 = p1;  //assigns all the contents of p1 to p2 and then to p3
    

    because that statement is basically:

    p3.operator=(p2.operator=(p1));
    

    If p2.operator=(...) didn't return *this you'd have nothing meaningful to pass into p3.operator=(...).