< Previous | Contents | Next >

Using Abstract Classes

At times you might want to define a class to act as a base for other classes, but it doesnt make sense to instantiate objects from this class because its so generic. For example, suppose you have a game with a bunch of types of creatures running around in it. Although you have a wide variety of creatures, they all have two things in common: They have a health value and they can offer a greeting. So, you could define a class, Creature, as a base from which to derive other classes, such as Pixie, Dragon, Orc, and so on. Although Creature is helpful, it doesnt really make sense to instantiate a Creature object. It would be great if there were a way to indicate that Creature is a base class only, and not meant for instantiating objects. Well, C++ lets you define a kind of class just like this, called an abstract class.


 

Introducing the Abstract Creature ProgramDeclaring Pure Virtual FunctionsDeriving a Class from an Abstract Class