www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is there a standard for whar opAssign/opOpAssign should return?

reply HSteffenhagen <cubicentertain gmail.com> writes:
In the https://dlang.org/spec/operatoroverloading.html opAssign
is declared as

void opAssign(S rhs);

in the example.

 From C++ I'm used to return *this when overloading assignment 
operators to allow chaining of assignments (or somewhat more 
rarely, weird tricks for if and while statements), is that not 
done in D as a rule or is the example just weird? Same question 
for the
opOpAssign family.
Mar 06 2016
parent Jonathan M Davis via Digitalmars-d-learn writes:
On Sunday, March 06, 2016 15:25:46 HSteffenhagen via Digitalmars-d-learn 
wrote:
 In the https://dlang.org/spec/operatoroverloading.html opAssign
 is declared as

 void opAssign(S rhs);

 in the example.

  From C++ I'm used to return *this when overloading assignment
 operators to allow chaining of assignments (or somewhat more
 rarely, weird tricks for if and while statements), is that not
 done in D as a rule or is the example just weird? Same question
 for the
 opOpAssign family.
void opAssign(S rhs); will work, but it's not the most flexible. Ideally, the various overloaded assignment operators would return "this" by ref. e.g. ref S opAssign(S rhs) { ... return this; } which is essentially what you do in C++. Without returning by ref, you can't chain assignments, which is why return by ref is preferable even if it's not required. The example in the documentation should probably be modified to return by ref, but void will work - just not with chained assignments. - Jonathan M Davis
Mar 06 2016