return *this

Hi, Im having problems understanding why do some member functions like
complex& operator+=(complex z){ re+=z.re; im+=z.im; return *this;} is using reference to itself as return type when void in my eyes would work just as fine

void operator+=(complex z){ re+=z.re; im+=z.im; }
By returning a self-reference, it allows operations to be chained together.

Consider the following:
 
  a += b += c;

If the underlined operation returned a void, the above statement would not be valid.

While chaining is probably unlikely with the += operator, other operators such as << and >> rely on chaining to allow multiple operations to be expressed on a single line.

It's a good habit to get into.


Last edited on
This makes sense and looks really useful. Tnx a lot :)
Last edited on
Topic archived. No new replies allowed.