Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function should return reference or object?

Let's discuss these two functions:

  1. complex& operator+=(const T& val);
  2. complex operator+(const T& val);

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?

like image 862
Narek Avatar asked Feb 26 '23 22:02

Narek


2 Answers

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.

like image 93
Marcelo Cantos Avatar answered Mar 08 '23 03:03

Marcelo Cantos


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.

like image 44
Scott Langham Avatar answered Mar 08 '23 03:03

Scott Langham