0

I have a the following class:

class CObj {
private:
    MyOtherClass _member;
};

and the following code that creates an instance of CObj class:

CObj* obj = new Cobj;

obj is allocated on the heap, but: Are CObj::_member allocated on the heap too? or on the stack?

crashmstr
  • 28,043
  • 9
  • 61
  • 79

3 Answers3

4

obj is a pointer allocated "on the stack"; the object obj points to is "on the heap", and, being obj->_member a member (=a part) of such an object, it's on the heap too.

In general, members, being part of the parent object, are allocated wherever their parent is stored.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
3

_member has automatic storage duration - it is allocated where it's owning object is allocated. So, if you create an instance of CObj with dynamic storage duration, like in your example, it will also be allocated in dynamic storage (the heap). If you create an object with automatic storage duration, it will be on the stack.

The problem with such questions is that C++ does not have any concept of stack and heap - it's just storage durations.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • `_member` does _not_ have automatic storage duration; it has the storage duration of the object which contains it. – James Kanze Oct 22 '13 at 12:45
  • And of course, it's not just storage durations; there's also object lifetime (which is determined when the constructors and the destructors run). – James Kanze Oct 22 '13 at 12:46
0

When you call new OS allocate as much memory as size of class on heap and call class contructor.

From this you can see that since MyOtherClass is in CObj and CObj holds MyOtherClass , MyOtherClass is also on heap in same space as CObj .

Luka Rahne
  • 10,336
  • 3
  • 34
  • 56