3

Why is it necessary when we overload the += operator to return a reference to the class? why the prototype is for instance ClassName& operator += (const ClassName& instance) instead of
void operator += (const ClassName& instance) ?

  • 6
    So you can do things like `a * (b += c);`. The built in compound operators return values; so should overloaded ones to avoid confusing people. – Shawn Nov 27 '19 at 19:39
  • @Shawn Though I wouldn't recommend chaining too many mutative operators together. I believe chaining 2 or more mutative operators is unspecified behavior. –  Nov 27 '19 at 20:01

2 Answers2

5

Several reasons.

That's what the builtin += and friends do; your overloaded version better act the same without a really good reason and documentation of the fact, or else people who use it expecting it to act like the built in ones will get upset.

The builtin ones act that way to allow them to be used as part of a larger expression like a + (b += c).

It makes defining an overloaded operator+() in terms of operator+=() and a copy constructor easy. Consider

class foo {
  foo& operator+=(const foo &b) {
    // Do stuff
    return *this;
  }
};
foo operator+(foo a, const foo &b) { // First argument passed by value, second by reference
  return a += b;
}

Making the compound operators class members and the plain operators freestanding is a common style suggestion; it allows the first argument to be of a different type as long as it can be converted to a foo: foo b; foo a = 1 + b;

(All examples are very contrived for demonstration purposes)

Shawn
  • 47,241
  • 3
  • 26
  • 60
  • That last one, while probably true, is weird. Normally, you should do it the other way around. –  Nov 27 '19 at 20:03
  • @Chipster, [not really](https://en.cppreference.com/w/cpp/language/operators#Binary_arithmetic_operators). – Evg Nov 27 '19 at 20:05
  • @Chipster What, define the compound version in terms of the non-compound operator? – Shawn Nov 27 '19 at 20:05
  • Reread [this question](https://stackoverflow.com/a/4421719/10957435) more closely, and realized I am wrong. So never mind. –  Nov 27 '19 at 20:07
-1

It is because the operator += has to be a left-hand-expression.

For instance, in a += ...; there is no way the result of the evaluation of this expression won't be a left-hand-expression (i.e., a += b + c + d;).

C. R. Ward
  • 93
  • 5