views:

48

answers:

1

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 ?

+8  A: 

Why [does the] heap object have a reference to stack memory?

Because you passed the local variable i by reference into the constructor of the Test object that you created dynamically, then the constructor stored that reference.

Why is this allowed?

In C++, you the programmer are responsible for ensuring that any pointers you use point to valid objects. The language doesn't have any guards to "protect" you from doing dumb things like this (there are, of course, good programming practices that exist to help you ensure that code you write shouldn't have issues like this).

An attempt to use an object after its lifetime has ended results in undefined behavior.

James McNellis