+ 1

Why in some cases we need to return reference from assignment operator overloading function?

1st Case :- Void operator=(const Test& obj) { If(this != &Obj) { x=new int; *x=*obj.x; } } 2nd Case :- Test& operator=(const Test& obj) { If(this != &Obj) { x=new int; *x=*obj.x; } return *this; } Above both the codes for assignment operator overloading works fine. Then why in Second case why we need to have return type "Test&" when normal void as return also works.

22nd Dec 2019, 7:43 AM
Amit chavare
Amit chavare - avatar
1 Odpowiedź
+ 2
We return a reference because then it allows us to chain multiple functions/operators. For example something like this: Test a, b, c; c = b = a; Or a.function1().function2(); ( If function1 returns a reference )
22nd Dec 2019, 8:41 AM
Dennis
Dennis - avatar