Is it necessary to overload the +=
operator even if we have already overloaded the +
and the =
operators?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With