Is it necessary to overload the +=
operator even if we have already overloaded the +
and the =
operators?
-
1Doing addition and then assignment is not the same thing as doing `+=`. Then end result *may* be the same, but different things are happening. This is especially important to remember if any overloaded operator have side-effects (intended or not). – Some programmer dude Feb 02 '16 at 11:09
2 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.
Yes, in general it's a good idea to provide the same behaviour with build-in types (such as int
) when implement operator overloading, to avoid confusing.
And without operator+=
, you have to use operator+
and operator=
to do the same thing. Even with RVO, once more copy will be applied.
If you decide to implement operator+=
, it's better to use it to implement operator+
for the consistency.

- 169,198
- 16
- 310
- 405