Skip to content

C++ inheritance for character class

An answer to this question on Stack Overflow.

Question

I have an assignment to recreate a game. I have to implement a list of characters. For example, I have the Character class which has only the name of the character.

Now, I need to create a Character Warrior who is an enemy in the game. Do I need to implement my inheritance like this: Character --> Enemy --> Warrior when my enemy class basically has no attributes. It's more of a classification than anything.

Is there a way to have an Enemy and a Warrior defined in the same class, where Warrior is of type Enemy, which is of type Character? There are going to be more enemies, but only one Warrior.

Thanks

Answer

You say the enemy class has basically no attributes.

That's the case now, but one reason for using an Enemy class and inheritance is that it better anticipates unknown future needs of the code by building in (nearly) transparent flexibility now.

You could certainly make a type for the Enemy class, but as you add more enemies, you may find that this solution requires more and more code in the form of switch statements and if clauses to check on the type.