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

旧街凉风 提交于 2019-12-02 20:54:38

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.

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=.

Consider what you are asking. You would want an expression, a + b, to return a reference to one of a or b, which would have the results of the expression. Thus you would modify one of a or b to be the sum of a and b. So you would want to redefine the semantics of the operator (+) to be the same as the operator (+=). And like @manuell said, you would thus allow (a + b) = c. The semantics you are suggesting are already offered by += and -=.

I think its fine if you return by value in overloaded assignment operator , that is because of associativity of assignment operator. consider this:

int a = b =c = 3 ;

here associativity is as followed: (a=(b=(c=3)))

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

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

you can see that x will be printed first , so if you return by value in overloading of << operator , return value will not be "lvalue" , while returning by refrence is a lvalue , so cascading of << operator can be achieve.

one more point , copy constructor will get called if you return by value. ( which is not the case with return by refrence)

samprat

The link shown below has better explanation I guess return value of operator overloading in C++

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!