creating an array of object pointers C++

Will it work?

Yes.

However, if possible, you should use a vector:

#include <vector>

std::vector<Ant*> ants;
for (int i = 0; i < num_ants; ++i) {
    ants.push_back(new Ant());
}

If you have to use a dynamically allocated array then I would prefer this syntax:

typedef Ant* AntPtr;
AntPtr * ants = new AntPtr[num_ants];
for (int i = 0; i < num_ants; ++i) {
    ants[i] = new Ant();
}

But forget all that. The code still isn’t any good since it requires manual memory management. To fix that you could to change your code to:

std::vector<std::unique_ptr<Ant>> ants;
for (auto i = 0; i != num_ants; ++i) {
    ants.push_back(std::make_unique<Ant>());
}

And best of all would be simply this:

std::vector<Ant> ants(num_ants);

Leave a Comment