Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why we use reference return in assignment operator overloading and not at plus-minus ops?

As I read in books and in the web, in C++ we can overload the "plus" or "minus" operators with these prototypes (as member functions of a 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 a reference to a Money object as a return value in the assignment operator overloading and not in the plus and minus operators?

like image 376
MinimalTech Avatar asked Jan 31 '14 16:01

MinimalTech


2 Answers

Returning a reference from assignment allows chaining:

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

(This would also work (in most cases) if the operator returned a copy of the new value, but that's generally less efficient.)

We can't return a reference from arithmetic operations, since they produce a new value. The only (sensible) way to return a new value is to return it by value.

Returning a constant value, as your example does, prevents move semantics, so don't do that.

like image 161
Mike Seymour Avatar answered Oct 13 '22 16:10

Mike Seymour


Because operator+ and operator- don't act on this object, but return a new object that is the summation (or subtraction) of this object from another.

operator= is different because it's actually assigning something to this object.

operator+= and operator-= would act on this object, and are a closer analog to operator=.

like image 24
John Dibling Avatar answered Oct 13 '22 16:10

John Dibling