'return type of operator+= while overloading
I have gone through some examples in the internet for operator overloading where the return type of operator+=
is T&
. Since we can't chain +=
like T a = b = c;
is it okay to declare the return type as void
. When using void
everything seems to work correctly. Is there any situation we have to avoid it?
For ex:
class MyInteger{
private:
int x;
public:
MyInteger(const int& a):x(a){}
void operator+=(const MyInteger& rhs){
x += rhs.x;
}
};
MyInteger a(10);
a += a; //No need to return anything because we can't chain
a = a + (a += a);
Solution 1:[1]
Another reason why you would want operator +=
to return a reference to the current object is when you want to overload operator +
. Since you're writing an integer class, it won't make a lot of sense if +=
were available, but +
wasn't.
Here is what operator +
would look like:
MyInteger MyInteger::operator+(const MyInteger& rhs)
{
MyInteger temp(*this);
return temp += rhs; // <-- Uses operator +=
}
The above could not work (or even compile) if operator +=
didn't return a reference.
Solution 2:[2]
As @Ant already pointed out, it can be chained, but it's not the only consideration. Consider
cout << (a += b);
for example - this won't work if there is no return.
The arithmetic operators themselves are nothing more than a human convention. Technically, you can even have +=
do -=
- it will build and possibly run for you (as long as you follow your new private conventions). Within C++, you should follow the conventions of the language: the clients of your code will expect that +=
self increments, and that
cout << (a += b);
will print out the result.
Solution 3:[3]
what nobody has mentioned is that this chaining behavior contradicts mathematical precedent. j += o += e will be evaluate such that j is incremented not by o as you would expect if equivalent binary chains were performed left to right, but as though we had written j += (o += e). Equivalent binary operations where order matters such as subtraction are always read left to right and discreetly in the absence of parenthesis. 5-4-3 is -2 and not 1. I have yet to see an explanation for why this isn't considered a design flaw. C++ seems to make a habit of leaving rabbit holes where anyone might hope for terra firma.
also cant reply yet, but the idea of using a += operator to overload the + operator seems a little hair-brained to me, idk.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | PaulMcKenzie |
Solution 2 | Ami Tavory |
Solution 3 | RedBeansAndRice |