Skip to main content
gamedev.net
🔒 Locked

Problems with "simple" inheritance

Started by matches81 Aug 10, 2006 at 8:09 AM 3 replies 1.2k views
Original Post
matches81
matches81
Hi there! I have a problem concerning inheritance or better said with overwriting inherited functions: I got a base class Entity, which supplies a function Update(float t). Furthermore I have a class Scene that keeps a std::vector< Entity * > and is meant to call that Update-function every frame. These classes are compiled into a DLL. Now the idea is that I can use this DLL in my main project, implement some classes that inherit from Entity, define new Update-functions there to get custom behaviour, and throw these derived classes at the std::vector< Entity * > in my scene, so the scene updates the entities automatically. However if I do something like this:

class Player : public Entity
{
...
    void Update(float t)
    {
        // do my update stuff here
    }
}
the only function that gets called by my Scene class is the Update-function from the base class Entity, not the one of the derived class Player like I´d expected. So my idea for a solution would be something like using type-IDs (perhaps int´s or strings) to identify which derived class that Entity* actually is and call the derived function explicitely, but that would be rather ugly I think and as far as my understanding of inheritance goes that shouldn´t be needed at all. Any help appreciated. Thx for reading.
_mycoplasma_
_mycoplasma_
did you remember to declare the base class function as being virtual?
magoora
magoora
I assume you did make the Entity::Update(float t) function virtual?
Otherwise I don't think the overwritten function in the subclass will get called on a pointer to Entity.

I may be wrong, I've never seen what happens / what is supposed to happen without applying virtual to a member that is intended to be inherited from.
Aardvajk
Aardvajk
That is a bit strange. Not sure if this is a DLL issue (although I've done this in the past the other way round - deriving classes in a DLL from a base class defined in the main project, then returning derived classes from the dll through a base class pointer and the virtual function mechanism seemed to work).

DLLs not withstanding, this should work:

class base{public:    virtual void update(){ }};class dervied : public base{public:    void update(){ }};std::list<base*> b;void f(){    b.push_back(new derived());    b.push_back(new derived());    b.push_back(new derived());    b.push_back(new derived());    for(std::list<base*>::iterator i=b.begin();i!=b.end();++i)        {        i->update(); // should call derived::update        }}
matches81
matches81
Ouch, that hurts.... using the virtual keyword fixed it. X-/
Thx for the fast response and help :)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.