return type of operator+= while overloading

Viewed 5840

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);
3 Answers

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.

Related