Why assignment operator return by reference?

I have code here that uses assignment operators that doesn't return by reference and it still works. So why does my book say you need to return by reference?

Here is a quote from my book:


The return type of operator= is a reference to the invoking object, so as to allow chained
assignments a=b=c.


The code below is from my book. I simply removed '&', in the original code that has assignment operators return by reference, from IntCell & operator=. This way the assignment operator no longer returns a reference, and it still works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60


#include <iostream>

using namespace std;

class IntCell
{
	public:
	explicit IntCell( int initialValue = 0 )
	{ storedValue = new int{ initialValue }; }

	~IntCell( ) // Destructor
	{ delete storedValue; }

	IntCell( const IntCell & rhs ) // Copy constructor
	{ storedValue = new int{ *rhs.storedValue }; }

	IntCell( IntCell && rhs ) : storedValue{ rhs.storedValue } // Move constructor
	{ rhs.storedValue = nullptr; }

        //Notice function type is not a reference.
	IntCell operator= ( const IntCell & rhs ) // Copy assignment
	{
		if( this != &rhs )
		*storedValue = *rhs.storedValue;
		return *this;
	}

        //Notice function type is not a reference.
	IntCell operator= ( IntCell && rhs ) // Move assignment
	{
		std::swap( storedValue, rhs.storedValue );
		return *this;
	}

	int read( ) const
	{ return *storedValue; }

	void write( int x )
	{ *storedValue = x; }

	private:
	int *storedValue;
};

int main()
{

	IntCell x;
	IntCell y{2};
	IntCell z{3};

	x = y = z;
	cout << "x = " << x.read() << endl;
	cout << "y = " << y.read() << endl;
	cout << "z = " << z.read() << endl;

	return 0;
}
Last edited on
Returning by value will work, but you are making unnecessary copies every time the = operator is called, so it isn't preferable.
Returning by value will work, but you are making unnecessary copies every time the = operator is called, so it isn't preferable.


So what the author wrote was just misleading. I knew it would work even though it would be inefficient, but the author gave the impression that I had to use return by reference.
If you write (x = y) = z;, returning by reference and value would have different behavior.

For assigment operator it really does not matter, aside form inefficiency and principle of least astonishment: any person would expect some concrete behavior from something like:
(x = y).set_field(5);
Topic archived. No new replies allowed.