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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With