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") ?
x
is a member ofA
. It is physically part of everyA
object, similar to the way your arm is physically part of you. So wherever theA
object is, on the stack, the heap, or wherever else, that is where itsx
member is. So to answer this question:No. It will be on the heap if the
A
that owns it is on the heap.