< Previous | Contents | Next >

Deriving a Class from an Abstract Class

When you derive a new class from an abstract class, you can override its pure virtual functions. If you override all of its pure virtual functions, then the new class is not abstract and you can instantiate objects from it. When I derive Orc from Creature, I override Creatures one pure virtual function with the following lines:

void Orc::Greet() const

{

cout << "The orc grunts hello.\n";

}

This means I can instantiate an object from Orc, which is what I do in main()

with the following line:

Creature* pCreature = new Orc();

The code instantiates a new Orc object on the heap and assigns the memory location of the object to pCreature, a pointer to Creature. Even though I cant instantiate an object from Creature, its perfectly fine to declare a pointer using the class. Like all base class pointers, a pointer to Creature can point to any object of a class derived from Creature, like Orc.

Next, I call Greet(), the pure virtual function that I override in Orc with the following line:

pCreature->Greet();

The correct greeting, The orc grunts hello., is displayed.

356 Chapter 10 n Inheritance and Polymorphism: Blackjack


Finally, I call DisplayHealth(), which I define in Creature.

pCreature->DisplayHealth();

It also displays the proper message, Health: 120.