0
\$\begingroup\$

I've got a little test put together that has a couple simple Components that are supposed to be added to an Entity, but the addComponent function isn't working; I think it's got something to do with typeid/component class inheritance, but I'm not sure. It seems to add a single entry to the map of type Component, but nothing else. Any help is much appreciated, thanks!

#include <iostream>
#include <unordered_map>
#include <typeinfo>

using namespace std;

//----------------------------------------------------------------------

//the base component
class Component {
    public:
    Component() {cout<<"new Component created\n";}
};

//----------------------------------------------------------------------

//a "thing" component
class Thing : public Component {
    public:
    Thing() {cout<<"new Thing created\n";}
};

//----------------------------------------------------------------------

//a "what" component
class What : public Component {
    public:
    What() {cout<<"new What created\n";}
};

//----------------------------------------------------------------------

class Entity {
    public:
    void addComponent(Component* c);
    template <typename T> T* getComponent();
    int componentCount();

    private:
    unordered_map<const type_info *, Component *> components;
};

//----------------------------------------------------------------------

void Entity::addComponent(Component* c) {
    components[&typeid(*c)] = c;
}

//----------------------------------------------------------------------

template <typename T>
T* Entity::getComponent() {
    if(components.count(&typeid(T)) != 0) {
        return static_cast<T*>(components[&typeid(T)]);
    } else {
        return nullptr;
    }
}

//----------------------------------------------------------------------

int Entity::componentCount() {
    return components.size();
}

//----------------------------------------------------------------------

int main(int argc, char* argv[]) {
    Entity e;

    e.addComponent(new What());
    e.addComponent(new Thing());

    cout<<e.componentCount()<<endl;

    return 0;
}
\$\endgroup\$
1
\$\begingroup\$

typeid can only see the derived type of an object if you have virtual methods. Otherwise it can only see the static type of an object. Since your base class almost certainly needs a virtual destructor, that's the easiest thing to change in your example.

class Component {
  public:
  Component() {cout<<"new Component created\n";}
  virtual ~Component() = default;
};
\$\endgroup\$
1
  • \$\begingroup\$ Ahhh, thought it might be something like that. Guess I need to read up a bit more on polymorphism and such. Thanks! :) \$\endgroup\$ Apr 24 '14 at 15:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.