Randy Schouten
Randy Schouten

Reputation: 39

Using a method from inherited class through base class

So I couldn't exactly find an answer anywhere. I have an entity class from which I create all my characters in the game. eg: Player inherits Entity.

Now what I want to do, is call the "Update" method in Player from the entity class. Is this possible? Because I need to do this for every new entity type I create now:

 foreach (Entity entity in entityList) {
                if (entity is Zombie) {
                    Zombie zombie = (Zombie)entity;
                    zombie.Update();
                }
                //new character here
            }

Thanks in advance!

Upvotes: 0

Views: 105

Answers (2)

Andy Prowl
Andy Prowl

Reputation: 126562

If the concept of "update" applies to all entities, you could make Update a virtual function of Entity and let Player override it. Then, inside member functions of Entity you would just have to invoke Update() on the particular Entity object and let the call be dispatched dynamically:

foreach (Entity entity in entityList) { entity.Update(); }

If Update() does not make sense for all Entitys, then having them as a virtual function of Entity would pollute the interface of that class, and it seems to me that your choice is correct.

You may also consider using the Visitor Pattern if you want to avoid the dynamic downcasts.

Upvotes: 1

Vesper
Vesper

Reputation: 18757

Override the Update() method in your subclasses. Then, just call entity.Update() for any encountered entity. This is what's called polymorphism.

Upvotes: 0

Related Questions