Accumulator
Accumulator

Reputation: 903

Best way to store all entities in C++ game

I'm trying to create a way to hold all entities in my C++ game, arrays wouldn't work since they are limited to one type. I need to store anything with the class Entity, and all it's derivatives in it. I've been trying all day to get a way to store all game entities in a way I can just loop through them all and draw them. Still haven't found a solution.

Upvotes: 1

Views: 1133

Answers (2)

Tas
Tas

Reputation: 7111

Assuming Entity is some base class that many things derive from, you can have a container (any container is fine, but std::vector is a good place to start unless you have some other specific requirements).

class Entity
{
    public:
    virtual void Draw() = 0;
};

class Atom : public Entity
{
public:
    void Draw() override {}
};

class Environment : public Entity
{
public:
    void Draw() override {}
};

int main()
{
    std::vector< std::shared_ptr<Entity> > entities;
    entities.push_back(std::make_shared<Atom>());
    entities.push_back(std::make_shared<Environment>());
    // Draw entities:
    for (size_t ent = 0; ent < entities.size(); ++ent)
    {
        entities[ent]->Draw();
    }
    return 0;
}

Upvotes: 4

Fej
Fej

Reputation: 29

You might be able to use std::vector. It has a lot of built-in functions for simple data manipulation, and you can use it with any type.

Upvotes: -2

Related Questions