One reason we use this is to avoid copying a large object, Another reason is to allow you to use a function call on the left side of the equal sign.
@CppNuts5 жыл бұрын
Correct!!
@DarkLevis7 жыл бұрын
I'd like to point out that you can actually get the correct value because 10 might still be at that address. Of course you can also get garbage, often depending on the rest of your code.
@kanishkjain71374 жыл бұрын
Thank you for the amazing videos. I had tried running the same code in Visual studio. It did not give me an error and also no garbage value as you said at 1:33 timestamp. Can you please explain to me why?
@akshhaayabitkaar6074 жыл бұрын
returning correct value for following code snippet
@CppNuts4 жыл бұрын
Got it, mean they are not erasing the memory right away.
@akshhaayabitkaar6074 жыл бұрын
int& fun() { int j = 10; return j; } int main() { int& c = fun(); return 0; } tested on VS
@CppNuts4 жыл бұрын
Soo, did it returned ?? If it did that mean they are not erasing the memory right away.
@akshhaayabitkaar6074 жыл бұрын
@@CppNuts yes, they are not erasing the memory.
@bluehornet67527 жыл бұрын
Why would you need to return a reference to an object that you already have a reference to? That's the point of passing in a reference in the first place. Your videos are generally good, but this one is pretty weak. I humbly suggest you should slow down a bit and think a little about the examples you give. This one doesn't make much sense.
@CppNuts7 жыл бұрын
Hi Tom B, Thanks for your suggestion this is really valuable comment. But i feel we can return reference if we have reference of something, because there could be a function chaining in caller side. Example: fun1(obj).fun2(); here in fun1() if we return reference to obj then fun2() will be called on reference to obj and make sense.
@bluehornet67527 жыл бұрын
So you'd have a reference to a reference then? Certainly you could do that if you wanted to chain function calls, but for this example...wow, that's a bit wacky. This function, the way you've presented it, uses a reference because you want to alter the value of 'x'. That's fine. It's perfect actually--just pass the reference, and change the value. Done. It does not need to return a reference, as you are not chaining function calls. So for the code you've presented, you simply don't need (or want) to return a reference as I see it. You could have shown a nice example of creating a dynamic array of integers, or of some other object, inside your function. And *then* your returned reference would have made sense. That said, I really enjoy your videos. You present some very good topics, and in general I think you do a great job--so that you very much for taking the time to make the videos and upload them to KZbin. I have found them to be a great refresher for me, as I haven't been writing in C++ for over a year now.