Where is the member array located?

Viewed 84

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?

2 Answers

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.

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.

Related