Array of Pointers

arrays, c++, pointers

Solution

You can do this with a pointer to pointer to your class.

MyClass ** arrayOfMyClass = new MyClass*[arrayLengthAtRuntime];
for (int i=0;i<arrayLengthAtRuntime;++i)
    arrayOfMyClass[i] = new MyClass(); // Create the MyClass here.

// ...
arrayOfMyClass[5]->DoSomething(); // Call a method on your 6th element

Basically, you're creating a pointer to an array of references in memory. The first new allocates this array. The loop allocates each MyClass instance into that array.

This becomes much easier if you're using std::vector or another container that can grow at whim, but the above works if you want to manage the memory yourself.

Problem

How can I get an array of pointers pointing to objects (classes) ? I need to dynamically allocate space for them and the length of array isn't determined until run-time. Can any one explain and tell me how to define it? and possibly explain them how it works, would be really nice :)

Original source