Michael Hutton
Michael Hutton

Reputation: 1

Confused about return by reference

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

Answers (3)

Jarod42
Jarod42

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

Alex Zywicki
Alex Zywicki

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

Maxim Egorushkin
Maxim Egorushkin

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

Related Questions