Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are return types of operators in C++?

I am reading the C++ Primer, in the overloaded operation chapter, the author gave an example:

// member binary operator: left-hand operand bound to implicit this pointer
Sales_item& Sales_item::operator+=(const Sales_item&);
// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);

then, the author explained:

This difference matches the return types of these operators when applied to arithmetic types: Addition yields an rvalue and compound assignment returns a reference to the left-hand operand.

I'm not quite sure about "compound assignment returns a reference to the left-hand operand". Can anyone elaborate on that, and relevant things, please?

like image 734
ipkiss Avatar asked May 04 '12 02:05

ipkiss


2 Answers

It means that you can do something like the following

a = 1; 
(a += 1) += 1;

and the result will be a == 3. This is because the left most call to += modifies a and then returns a reference to it. Then the next += operates on the reference to a and again adds a number to it.

On the other hand, the normal + operator returns a copy of the result, not a reference to one of the arguments. So this means that an expression such as a + a = 3; is illegal.

like image 108
Davis King Avatar answered Oct 14 '22 16:10

Davis King


a = a + b;

is also

a += b;

which is equivalent to

a.operator+= (b)

operator += supports compound assignment:

(a += b) += c;

is equivalent to

a.operator+= (b).operator+= (c);

The last line would not be possible if a value was returned instead of an rvalue.

Consider the following:

c = a + b;

is also

c = a.operator+ (b);

writing

a.operator+ (b) = c;

has no effect because the value of a is not changed.

like image 36
Vinnie Falco Avatar answered Oct 14 '22 15:10

Vinnie Falco