< Previous | Contents | Next >

Introducing Inheritance

One of the key elements of OOP is inheritance, which allows you to derive a new class from an existing one. When you do so, the new class automatically inherits (or gets) the data members and member functions of an existing class. Its like getting the work that went into the existing class for free!

Inheritance is especially useful when you want to create a more specialized version of an existing class because you can add data members and member functions to the new class to extend it. For example, imagine you have a class Enemy that defines an enemy in a game with a member function Attack() and a

331

332 Chapter 10 n Inheritance and Polymorphism: Blackjack


data member m_Damage. You can derive a new class Boss from Enemy for a boss. This means that Boss could automatically have Attack() and m_Damage without you having to write any code for them at all. Then, to make a boss tough, you could add a member function SpecialAttack() and a data member DamageMultiplier to the Boss class. Take a look at Figure 10.1, which shows the relationship between the Enemy and Boss classes.


image

Figure 10.1

Boss inherits Attack() and m_Damage from Enemy while defining SpecialAttack() and

m_DamageMultiplier.


One of the many advantages of inheritance is that you can reuse classes youve already written. This reusability produces benefits that include:

n Less work. Theres no need to redefine functionality you already have.

Once you have a class that provides the base functionality for other classes, you dont have to write that code again.

n Fewer errors. Once youve got a bug-free class, you can reuse it without errors cropping up in it.

Introducing Inheritance 333


n Cleaner code. Because the functionality of base classes exist only once in a program, you dont have to wade through the same code repeatedly, which makes programs easier to understand and modify.

Most related game entities cry out for inheritance. Whether its the series of enemies that a player faces, squadrons of military vehicles that a player commands, or an inventory of weapons that a player wields, you can use inheritance to define these groups of game entities in terms of each other, which results in faster and easier programming.


 

Introducing the Simple Boss ProgramDeriving from a Base ClassInstantiating Objects from a Derived ClassUsing Inherited Members