Hi, I have following code
class Test
{
public:
int &ref;
int a;
Test(int &x)
:ref(x)
{
cout<<"Address of reference "<<&ref<<endl;
cout<<"&a : "<<&a<<endl;
cout<<"this = "<<this<<endl;
}
};
int main()
{
Test *pObj = NULL;
{
int i = 10;
cout<<"Address of referent "<<&i<<endl;
pObj = new Test(i);
}
pObj->ref++;
cout<<pObj->ref;
}
Output is :
Address of referent 002DFB3C Address of reference 002DFB3C &a : 00734C94 this = 00734C90
As you can see, Test object is being created dynamically. variable i which is stored on stack is being sent as parameter to constructor of Test class. I printed the address of variables i, ref and a.
Question: variable i will be destroyed once program control exits the block in which it is declared. But dynamically allocated object's member variable ref would still be refering to the stack address(Address of i). Able to use ref after the death of i.
Why heap object has reference to stack memory ? Why is this allowed ?