Reputation: 1
I am confused by the following example:
class complex {
double re, im;
public:
complex(double r, double i) : re{r}, im{I} ()
complex& operator+= (const complex&z) { re += z.re; im += z.im; return *this; }
};
I don't understand why the return type from the operator +=
is by reference, since re
and im
are getting updated. I also do not understand why *this
is included.
Upvotes: 0
Views: 81
Reputation: 218323
By convention, we try that operator
for class works as for built-in.
and
int i = 0;
(i += 40) += 2;
is valid.
So returning by reference allows that for classes.
Upvotes: 1
Reputation: 2313
First:
Your operator += is not properly declared. It should be
complex& operator+=(complex const& other){...}
Second to answer your actual question, you are returning *this because the += operator is a compound assignment operator which is modifying the internal state of the variable being assigned to. So you return a reference to the variable that "this" is pointing to.
Upvotes: 0
Reputation: 136515
It could as well return void
.
The C++ convention is that operator+=
returns a reference to its left-hand operand, so that you can write an expression like if((x += y) > 10)
.
Upvotes: 1