I am trying to understand functions returning a reference. For that I have written a simple program:
#include<iostream>
using namespace std;
class test
{
int i;
friend test& func();
public:
test(int j){i=j;}
void show(){cout<<i<<endl;}
};
test& func()
{
test temp(10);
return temp; //// Address of temp=0xbfcb2874
}
int main()
{
test obj1(50); // Address of obj1=0xbfcb28a0
func()=obj1; <= Problem:The address of obj1 is not changing
obj1.show(); // // Address of obj1=0xbfcb28a0
return 0;
}
I ran the program using gdb and observed that the address of obj1 still remains same, but I expect it to get changed to 0xbfcb2874. I am not clear with the concept. Please help.
There are several problems in your code:
(1) That is not how you want to return a reference.
temp(10)is an automatic (i.e. resides in stack) variable and will be destroyed once your program goes out of scope of thetestfunction. A better way to show this would be to return a reference to a variable passed (e.g. for chaining of calls):(2) You are assigning the value of
obj1tofunc(), while what you want would be to assign the return value offunc()to a variable. Try this:(3)
func()need not be a friend ofTest. In fact, it should not. Afriendclass/functions allow the class/functions to access private members ofTest. That is not what you want to do too often.