Are member variables of an object on the heap also automatically on the heap?

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 if it was not specifically new? And in this case, Y stands out on the stack (and, of course, goes out of scope), right?

I wonder if I passed when my wires crossed, when they tried to imagine how the objects are stored in memory.

+7
c ++
source share
4 answers

Yes. This is on the heap. Basically, the space allocated to an object on the heap is large enough to hold all of its member variables.

+17
source share

Yes, it is on the heap.

Some information: When you use the β€œnew” operator, it happens that the compiler allocates enough heap space for the class, including all the space needed for all member variables (which can also be classes, in which case their size must be calculated etc.).

After that, the constructor is called in the data element classes, then in the class itself.

Whenever you do not specifically allocate memory in a heap (usually using a new operator or calling a function that does this for you), memory is allocated on the stack, for example, the y variable in your example.

+5
source share

I think half of your question went unanswered: you asked if there is Y on the stack, this is really correct.

+3
source share

Y is on the stack because it is created locally; X is on the heap.

0
source share

All Articles