Under which circumstances must we have methods return by reference? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Under which circumstances must we have methods return by reference?

8th Dec 2019, 4:17 AM
Moses Odhiambo
Moses Odhiambo - avatar
2 Answers
+ 4
when we would like to change the value of the variable permanently!
8th Dec 2019, 4:46 AM
Rohit
+ 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๐Ÿ˜๐Ÿค
8th Dec 2019, 5:03 AM
๐Ÿ‡ฎ๐Ÿ‡ณOmkar๐Ÿ•‰
๐Ÿ‡ฎ๐Ÿ‡ณOmkar๐Ÿ•‰ - avatar