Let's say I have a very simple class
class C {
private:
int _a;
int _b;
public:
C (int a, int b) :_a { a }, _b { b } {}
int a () { return _a; }
int b () { return _b; }
bool operator== (C c) {
return this->_a == c.a() && this->_b == c.b();
}
};
and I want to overload the operator +=
such that
C foo(8, 42);
C bar(1, 1);
C zoo(9, 43);
foo += bar;
assert(foo == zoo);
runs fine.
As far as I've read other people code, I should write something like
C operator+= (C c) {
return { this->_a += c.a(), this->_b += c.b() };
}
but to my understanding, return
ing something is useless. Indeed, the assertion above does not fail even when I overload +=
as
void operator+= (C c) {
this->_a += c.a();
this->_b += c.b();
}
or
C operator+= (C c) {
this->_a += c.a();
this->_b += c.b();
return C(0,0);
}
TL;DR: why shouldn't I return void when overloading +=
?