class A
{
public:
A();
~A();
int X;
};
A::A()
{
X = 5;
int Y = 4;
}
//..... in another file
A * objectOnHeap = new A();
In this case, since "objectOnHeap" is on the heap, is X also on the heap even though it wasn't specifically new'd up? And in this case Y is allocated on the stack (and of course goes out of scope), correct?
I am wondering if I have gotten my wires crossed when trying to envision how objects are stored in memory.
Yes. It's on the heap. Basically, the space allocated to an object on the heap is big enough to hold all its member variables.
Yes, it's on the heap.
Some details: When you use the "new" operator, what happens is that the compiler allocates enough space on the heap for the class, including all the space needed for all the member variables (which might also be classes, in which case their size needs to be computed too, etc.).
After this, the constructor is called on the data member classes, then on the class itself.
Whenever you don't specifically allocate memory on the heap (usually by using the new operator, or calling a function that does that for you), the memory is allocated on the stack, like the variable y in your example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With