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?
Strictly speaking, the result of a copy assignment operator doesn't need to return a reference, though to mimic the default behavior the C++ compiler uses, it should return a non-const reference to the object that is assigned to (an implicitly generated copy assignment operator will return a non-const reference - C++03 ...
The assignment operators return the value of the object specified by the left operand after the assignment. The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.
An assignment operator is the operator used to assign a new value to a variable, property, event or indexer element in C# programming language. Assignment operators can also be used for logical operations such as bitwise logical operations or operations on integral operands and Boolean operands.
If a class do not have any pointers, then we do not need to create assignment operator and copy constructor. C++ compiler creates copy constructor and assignment operator for each class. If the operators are not sufficient, then we have to create our own assignment operator.
There is no need to avoid this, unless the book is aimed at programmers that commonly write (x=y)=z
when they mean x=y=z
. In practice, nobody in their right mind writes that, so the precaution is entirely unnecessary. It also forbids some other terse constructs, such as (x=y).nonConstMember()
, that hardly anyone writes but that might be useful in some contexts (although they shouldn't be over-used).
@ybungalobill is right, get a better book.
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With