Why do we use referential return when overloading the assignment operator, and not in plus or minus ops?

As I read in books and on the Internet, in C ++ we can overload the plus or minus operators with these prototypes (as member functions of class Money ):

const Money operator +(const Money& m2) const;

const Money operator -(const Money& m2) const;

and for the assignment operator with:

const Money& operator =(const Money& m2);

Why use the reference to the Money object as the return value in the overload of the assignment operator, and not in the plus and minus operators?

+7
c ++ operators operator-overloading
source share
5 answers

Returning a link from an assignment allows you to link:

 a = b = c; // shorter than the equivalent "b = c; a = b;" 

(This will also work (in most cases) if the operator returned a copy of the new value, but it is generally less efficient.)

We cannot return a link from arithmetic operations, since they produce a new value. The only (reasonable) way to return a new value is to return it by value.

Returning a constant value, as your example shows, prevents the semantics of movement, so don't do this.

+11
source share

Since operator+ and operator- do not act on this object, but return a new object, which is the summation (or subtraction) of this object from another.

operator= differs in that it really assigns something to this object.

operator+= and operator-= will act on this object and become closer to operator= .

+4
source share

Think what you ask. You need the expression a + b to return a link to one of a or b that will have the results of the expression. So you must change one of a or b to be the sum of a and b. Therefore, you would like to redefine the semantics of the operator (+) in the same way as the operator (+ =). And, as @manuell said, you would allow (a + b) = c . The semantics that you propose are already proposed + = and - =.

+1
source share

The link shown below has a better explanation, I think it returns the operator overload value in C ++

0
source share

I think this is normal if you return by value in the overloaded assignment operator, that is, due to the associativity of the assignment operator. consider this:

int a = b = c = 3;

here the associativity is as follows: (A = (b = (c = 3)))

but consider the operation iostream cout <x <y <z;

here the associativity is as follows: (((cout <x) <y) <z);

you can see that x will be printed first, so if you return by value when the <<operator is overloaded, the return value will not be an “lvalue”, while returning by refrence is an lvalue, so cascading <<operator can be achieved.

another point, the copy constructor will be called if you return by value. (which does not match return with refrence)

0
source share

All Articles