I am reading a book about C++ and more precisely about the operator overloading.
The example is the following:
const Array &Array::operator=(const Array &right)
{
// check self-assignment
// if not self- assignment do the copying
return *this; //enables x=y=z
}
The explanation provided by the book about returning const ref instead of ref is to avoid assignments such as (x=y)=z. I don't understand why we should avoid this. I understand that x=y is evaluated first in this example and since it returns a const reference the =z part cannot be executed. But why?
(x=y)
means x.operator=(y)
, which returns the object x
. Therefore, (x=y)=z
means (x.operator=(y)).operator=(z)
. The expression in parens sets x
to y
and returns x
, and then the outer bit sets x
to z
. It does not set y
to z
as you might expect, and as the expression x = y = z
does.
This behavior is counter-intuitive (they should all be equal after the assignment, right?); returning a const reference makes it impossible and avoids the problem.