I am wondering what happens when you return int&. Lets jump to the example. I have a simple class Foobar storing one int. Lets have a look at this function:
Foobar showObjectsValue() {
Foobar b(50);
return b;
}
It returns copy of a local object so when I call this function I actually get some data instead of some trash. But when I do something like this:
Foobar& showObjectsValue() {
Foobar b(50);
return b;
}
It returns garbage because after we exit scope of the "showObjectsValue()" object "b" gets popped from the memory stack and we return reference to this popped object (correct me if I am wrong). But I don't know what is happening in case of returning int instead of object.
This function:
int& showIntegerValue() {
int i = 50;
return i;
}
and this function:
int showIntegerValue() {
int i = 50;
return i;
}
return the same value, both give me int = 50. So can someone explain what actually is going on in case of returning reference to local integer and local object?