0

For fun I decided to try to make a simple entity component system. I have a list that contains all Components and I made a function called getPositionComponent that takes the entity ID and returns the position component related to that entity. All of the components I make are derived from the Components class.

struct Component
{
public:
    std::string readableName;
    Component::Component();
    Component(std::string name);
    virtual ~Component();
};

Position component

 struct PositionComponent :
        public Component
    {
    public:
        PositionComponent(int x, int y);
        ~PositionComponent();
        int x, y;
    };

This is how getPositionComponent looks like

PositionComponent* ComponentManager::getPositionComponent(int entityID) {
    int index = entitiesLookup_[entityID] + positionComponentsLookup_[entityID];

    Component *comp = &components_[index];
    PositionComponent* postionComponent = dynamic_cast<PositionComponent*>(comp);

    if (postionComponent != nullptr)
        return postionComponent;
    return nullptr;
}

When I run this, it always returns a nullptr when I use dynamic_cast. While debbuging I can confirm that Component *comp = &components_[index]; returns the correct component type.

On a side note, I was reading one article where for an MMO they used SQL to store components. How slow/fast would sql be for pulling data locally from components in the game loop in a single player game?

Ziamor
  • 493
  • 1
  • 7
  • 11

1 Answers1

2

I'm going to hazard a guess here...

You are storing a list of Compoents in a std::vector<Component>. When you store a derived class of Component in a std::vector, you lose the derived class part. Hence, the dynamic_cast fails.

You can fix that problem by storing a list of pointers to Componentsin a `std::vector.

You can avoid errors like this by making sure that the base class is an abstract base class.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Ah yes I am indeed using Vectors, Ill try changing it to a list of pointers, thanks. – Ziamor May 19 '14 at 02:06
  • 1
    A `std::vector` is copying the values, and you end up slicing `Derived` objects to `Component` base type. – vsoftco May 19 '14 at 02:33