• Advertisement
Sign in to follow this  

C++ polymorphism question

This topic is 4312 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello all, I have yet another question about C++ polymorphism. We had an interesting issue where we discovered that a virtual method was calling the superclass' version instead of the subclass version. We were confused, and this is what we discovered: There is a class called GameEntity(). Game Entity has a method like so: virtual entType GetType(){ return General_Type; } There is also a class called GunnerEntity(), which publicly inherits from GameEntity. Gunner Entity overrides the method: entType GetType(){ return Gunner_Type; } But the problem was, we were setting a local struct full of entity data from WITHIN the GameEntity constructor using the GetType() call. This is something that has to happen for each entity, so we figured we would put it in the superclass, and not make every entity re-do the code in their own constructors. My understanding is, a virtual method will always call the subclass' implementation if there is one. Yet it was calling the superclass method from within the GameEntity constructor. Is this just a restriction on code from within the superclass constructor, even if eventually the instance will become a subclass? It would make sense that the virtual function table might not be set up while you're still in the superclass' constructor. I'd appreciate any advice on this. Thanks much! jujumbura

Share this post


Link to post
Share on other sites
Advertisement
Quote:
Original post by jujumbura
Is this just a restriction on code from within the superclass constructor, even if eventually the instance will become a subclass? It would make sense that the virtual function table might not be set up while you're still in the superclass' constructor.


Thou hast hit it. See this and this.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement