Why overloading operator= return reference?


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
class Test
{
public:
	int a;
	Test() : a(0) {}
	Test(int x) : a(x) {}
	Test& operator=(const Test& rhs)
	{
		if(this == &rhs)
			return *this;
		a = rhs.a;
		return *this;
	}
};


int main()
{
	Test t(5);
	Test t2;
	Test t3;
	t3 = t2 = t;
	cout << t3.a << endl;
	cout << t.a << endl;
	return 0;

}


I found somewhere it says for chain assignment, but I found return by value just works fine. for saving time?
Well, then try the following code when the copy assignment operator returns a value instead of a reference.

( t3 = t2 ) = t;

What will be the value of t3?
Last edited on
Thanks a lot,
vlad from moscow
, you helped me a lot!!!!!
Topic archived. No new replies allowed.