Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 546
BuckFilledPlatypus Avatar asked Sep 22 '09 16:09

BuckFilledPlatypus


2 Answers

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.

like image 60
mmx Avatar answered Sep 25 '22 12:09

mmx


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.

like image 32
Edan Maor Avatar answered Sep 23 '22 12:09

Edan Maor