3

Given the following code:

class MyClass
{
public:
    char array[10];
};

int main()
{
    MyClass *p = new MyClass;
...
}

As far as I understand - new allocates the object on the heap. But also, the array is allocated on the stack (no new operator).

So, is the array allocated on heap (because the object is at the heap) or on the program stack?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
dushkin
  • 1,939
  • 3
  • 37
  • 82
  • @George They mean the free-store – Post Self Nov 12 '17 at 14:48
  • 2
    You should familiarize yourself with [storage duration](http://en.cppreference.com/w/cpp/language/storage_duration). – Captain Obvlious Nov 12 '17 at 14:48
  • 4
    Possible duplicate of [Class members and explicit stack/heap allocation](https://stackoverflow.com/questions/10836591/class-members-and-explicit-stack-heap-allocation), or [Are the members of a heap allocated class automatically allocated in the heap?](https://stackoverflow.com/questions/12826722/c-are-the-members-of-a-heap-allocated-class-automatically-allocated-in-the-hea), or [Class members allocation on heap/stack?](https://stackoverflow.com/questions/2820477/class-members-allocation-on-heap-stack-c), or probably many more – underscore_d Nov 12 '17 at 14:49

2 Answers2

6

But also, the array is allocated on the stack (no new operator)

No, the array is a member of the object. It's a part of it. If the object is dynamically allocated, then all of its parts are too.

Note I said all of its parts. We can tweak your example:

class MyClass
{
public:
    char *p_array;
};

int main()
{
    char array[10];
    MyClass *p = new MyClass{array};

    // Other code
}

Now the object contains a pointer. The pointer, being a member of the object, is dynamically allocated. But the address it holds, is to an object with automatic storage duration (the array).

Now, however, the array is no longer part of the object. That disassociation is what makes the layout you had in mind possible.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
4

What MyClass *p = new MyClass; really means is that you want to allocate sizeof(MyClass) bytes on the heap/free store to store every member of MyClass. The size of a class is based on it's members. array is a member of MyClass and thus because MyClass is allocated on the free store, so is array.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122