Alpha Canis Majoris
Alpha Canis Majoris

Reputation: 33

Overloading compound assignment operators in C++

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) ?

Upvotes: 3

Views: 280

Answers (2)

C. R. Ward
C. R. Ward

Reputation: 93

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;).

Upvotes: -1

Shawn
Shawn

Reputation: 52334

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)

Upvotes: 5

Related Questions