akif
akif

Reputation: 12334

Array of Pointers

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 :)

Upvotes: 3

Views: 777

Answers (4)

Fernando N.
Fernando N.

Reputation: 6439

Use boost::ptr_vector and forget both array and pointer headaches:

boost::ptr_vector<animal> vec;
vec.push_back( new animal );
vec[0].eat();

You can add elements dynamically and you don't need to worry about deleting them.

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564413

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.

Upvotes: 10

Daniel Bingham
Daniel Bingham

Reputation: 12914

I can't edit or comment yet so I have to post it in an answer: What Reed Copsey said, but with one fix. When you access elements of your array of pointers you need to access the members like this:

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

I use this method a lot to implement my own dynamic size arrays (what std::vector is), mostly because I have Not Invented Here syndrome but also because I like to customize them to my particular use.

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421988

Use std::vector instead. It's designed to dynamically resize the collection as needed.

#include <vector>
// ...
std::vector<Class*> vec;
vec.push_back(my_class_ptr);
Class* ptr = vec[0];

Upvotes: 15

Related Questions