C++ Pointer Object Location

76 views Asked by At

I have the following C++ code:

struct B {
    int c;
    int d;
}

struct A {
    int a;
    B x;
}

int main() {
    A * ptr = new A;
    ptr->a = 1;
    ptr->x.c = 2;
    ptr->x.d = 23;

    // a lot of lines of codes later ...

    // Will the following values be guranteed?
    cout << ptr->x.c << endl;
    cout << ptr->x.d << endl;
}

After declaring a new "struct A" on the heap will ptr->x be declared on the stack or the heap? If i want x to be on the heap, must i declare property x as a pointer (and hence, initialize it with "new") ?

2

There are 2 answers

0
Benjamin Lindley On BEST ANSWER

x is a member of A. It is physically part of every A object, similar to the way your arm is physically part of you. So wherever the A object is, on the stack, the heap, or wherever else, that is where its x member is. So to answer this question:

If i want x to be on the heap, must i declare property x as a pointer (and hence, initialize it with "new") ?

No. It will be on the heap if the A that owns it is on the heap.

0
Simon Gibbons On

ptr->x will be on the heap.

This is because when you create your instance of A it will have enough memory allocated for all of it's members. Which includes a member of type B.