c++ - Why overloading of += never return nothing in other people's code? -


let's have simple class

class c {      private:         int _a;          int _b;      public:         c (int a, int b) :_a { }, _b { b } {}         int () { return _a; }         int b () { return _b; }         bool operator== (c c) {             return this->_a == c.a() && this->_b == c.b();         } }; 

and want overload operator += such that

c foo(8, 42); c bar(1, 1);  c zoo(9, 43); foo += bar; assert(foo == zoo); 

runs fine.

as far i've read other people code, should write like

c operator+= (c c) {     return { this->_a += c.a(), this->_b += c.b() }; } 

but understanding, returning useless. indeed, assertion above not fail when 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 return void when overloading +=?

returning left-hand side of expression allows chain operators, or use result of assignment in single line, i.e.

int c = += b;//this ugly :'( 

or

if(a+=b) { } 

also, behaviour have on built-in types (paragraph 13.6 of c++ standard), idea mimic custom clases


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -