Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading compound assignment operator

Is it necessary to overload the += operator even if we have already overloaded the + and the = operators?

like image 665
Walidix Avatar asked Sep 12 '25 09:09

Walidix


1 Answers

Are you going to use the += operator? If yes, then yes, you should overload it.

The compiler does not automatically create one even if you have overloaded the operator+ and assignment operator. You can implemented them in terms of each other, but they all need to be implemented. In general, the addition and assignment will do the same thing as the compound assignment, but this is not always the case.

In general, when overloading the arithmetic operators (+, - etc.) you should do them with their associated compound assignments as well (+=, -= etc.).

See the "Binary arithmetic operators" on cppreference for some canonical implementations.

class X
{
 public:
  X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
  {                           // but often is, to modify the private members)
    /* addition of rhs to *this takes place here */
    return *this; // return the result by reference
  }

  // friends defined inside class body are inline and are hidden from non-ADL lookup
  friend X operator+(X lhs,        // passing lhs by value helps optimize chained a+b+c
                     const X& rhs) // otherwise, both parameters may be const references
  {
    lhs += rhs; // reuse compound assignment
    return lhs; // return the result by value (uses move constructor)
  }
};

This SO Q&A for some basic rules on overloading.

like image 166
Niall Avatar answered Sep 14 '25 00:09

Niall