Effective C++ item 10: Have assignment operators return a reference to *this.

If you want to concatenate assignments like:

1
2
int x, y, z;
x = y = z = 15;

The convention is to make the assignment operator return a reference of *this. And then this  applies to all assignment operators something like +=, -=, etc.. It’s just an convention to follow, but there is no reason to not follow it:

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 *this;
}
Widget& operator=(const Widget& rhs)
{
...
return *this;
}
Widget& operator=(int rhs)
{
...
return *this;
}
...
};

And I’ll talk about handle self assignment in next post.

Reference:
“Effective C++” Third Edition by Scott Meyers.