Let's discuss these two functions:
Where "complex" is a name of a class that implements for example complex variable.
So first operator returnes reference in order to be possible to write a+=b+=c ( which is equivalent to b=b+c; a=a+b;).
Second operator returnes and objec(NOT A REFERENCE), be we still able to write a=b+c+d.
Who could explain me this nuance? What is the difference between returning reference or object?
The assignment operators support multiple application to the same object:
(a += b) += c;
Which will add both b
and c
to a
. For this to work, a += b
must return a reference to a
. The addition operator, however, doesn't require this, since the expression b + c + d
has no side-effect. Only the final assignment to a
has a side-effect.
In 1, a+=b, the += operator modifies a. Therefore it can return a reference to itself, because a itself is the correct result of the operation.
However, in 2. a new object is required because a+b returns something that is not a, so returning a reference to a wouldn't be correct.
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