+ 2
Under which circumstances must we have methods return by reference?
3 Respostas
+ 4
when we would like to change the value of the variable permanently!
+ 4
𝕄𝕠𝕤𝕖𝕤 𝕆𝕕𝕙𝕚𝕒𝕞𝕓𝕠 ,
IMO you shouldn't return reference to a local object i.e created inside the function which returns it.
MyClass & fun()
{
MyClass obj;
return obj;
}
Looks alright? It isn't! You are returning a reference to object that is going out of scope. It's limited to that `fun` function (local obj). You'll be referring to object that doesn't exist.
Returning object reference isn't completely useless. You may return object references that aren't local to that function.
A practical example:
While overloading stream operators << and >> we actually return stream object reference. This helps in cascading of multiple operators.
See you may overload stream operators << for a class to print it's content.
As it returns reference to stream on which it operates you can add many such << operators.
This may help.
https://code.sololearn.com/cWw85pS9Dfg1/?ref=app
Please ,*anyone* feel free to correct me😁🤝