user1139252
user1139252

Reputation: 261

Class members created on stack or heap?

Need to know if such a 3d matrix would be created in the stack or on the heap and if its on the stack how to new it and initialize default values correctly (memset)

class Matrix {
     protected:
         int n[9000][420]; // is stack or heap if VVV is pointer?
};

void main()
{
         Matrix* t = new Matrix(); // created on heap
}

Upvotes: 1

Views: 5741

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 477040

The array n is a direct member of the class Matrix, so any object instance of this type contains the data for n directly. In particular, if you create a dynamic object in dynamically allocated memory, then the array will be there; and if you create an automatic object, the array will be reside the automatic memory as well.

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124642

It all comes down to how you create the parent object.

MyClass {
    int n[10];
};

int main(...) {
    MyClass *c1 = new MyClass; // everything allocated on heap, 
                               // but c1 itself is automatic
    MyClass c2;                // everything allocated on stack
    // ...
}

Heaps and stacks are of course an implementation detail, but in this case I think it's fair to specify.

Upvotes: 5

Related Questions