This page looks best with JavaScript enabled

Item-10 Have assignment operators return a reference to *this

 ·  ☕ 1 min read · 👀... views

As title suggests.

Assignment is able to chain together:

1
2
int x,y,z;
x = y = z = 15;  // chain of assignment

Basically, the chain is parsed from right to left, so the result of the updated z is assigned to y, then the result of the second assignment (the updated y) is assigned to x:

1
x = (y = (z = 15));

In order to achieve this, we need to implement the assignment operators (as well as +=, -=, *=, etc) in the following convention, where we make the assignment return a reference to its left-hand argument:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Widget {
public:
    ...
    Widget& operator=(const Widget& rhs)  // return type is a reference to the current class
    {
        ...
        return *this;  // return the left-hand object
    }
    Widget& operator=(int rhs)
    {
        ...
        return *this;  // even if the right-hand side parameter type is unconventional
                       // we can still apply this convention
    }
    Widget& operator+=(const Widget& rhs)
    {
        ...
        return *this;
    }
    ...
};
Share on
Support the author with