why function chaining is working without returning reference from overloaded operator | Sololearn: Learn to code for FREE!
+ 1

why function chaining is working without returning reference from overloaded operator

Hi Please refer below code: https://code.sololearn.com/cv3zt0kMdApu why c0+c2+c3 is working fine even though I am not returning reference from overloaded operator?

30th Mar 2021, 5:42 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
7 Answers
+ 5
References to the object (*this) are typically returned from: Prefix increment Prefix decrement Assignment Compound assignment (+=, ...) These operators usually work on and change the object itself, so you return a reference to be able to correctly chain calls to "mutating" operators. Most other operators, like +, -, ..., do not change their parameters and therefore need to create a new instance to store the result, which needs to be returned as a copy due to scope rules. Other operators might return references as well, just usually not to the object, e.g. the subscript operator. However, ultimately it depends upon what your operator does. Since you are free to overload them however you want, it might function in a completely different way. These are just suggestions because most people will expect your overloaded operator to work in a certain way, based on their experiences with how it behaves normally.
30th Mar 2021, 9:03 AM
Shadow
Shadow - avatar
+ 2
I'm guessing it should work the way it would with regular numbers c4 = ( ( c0 + c1 ) + c2 ) I could be wrong though. Let's see what community says ...
30th Mar 2021, 6:17 AM
Ipang
+ 1
Yes lpang is right. first c0 and c1 is added and then the returned object gets added to c2.
30th Mar 2021, 6:21 AM
Carlos
Carlos - avatar
+ 1
Seems this is logically correct and working also.... Do we never need reference return from overloaded operator ? This is making me confuse
30th Mar 2021, 7:48 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Yeah got it... Thank you so much Shadow
30th Mar 2021, 9:10 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Does a reference have to be returned for the operator to work?
30th Mar 2021, 6:01 AM
Ipang
0
No it's not mandatory... For two object addition , it's fine... My query arised due to c0+C1+C2 as I thought it should be a case of function chaining..
30th Mar 2021, 6:03 AM
Ketan Lalcheta
Ketan Lalcheta - avatar