BuckFilledPlatypus
BuckFilledPlatypus

Reputation: 2178

Are member variables of an object that is 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 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.

Upvotes: 11

Views: 3258

Answers (4)

Wangge
Wangge

Reputation: 462

Y is on stack since is created locally; X is on the heap.

Upvotes: 0

zenerino
zenerino

Reputation: 356

I guess half of your question remained unanswered: you were asking if Y is still allocated on the stack, that's correct indeed.

Upvotes: 3

Edan Maor
Edan Maor

Reputation: 10052

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.

Upvotes: 5

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421988

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.

Upvotes: 18

Related Questions