< Previous | Contents | Next >
Introducing the Abstract Creature
The Abstract Creature program demonstrates abstract classes. In the program, I define an abstract class, Creature, which can be used as a base class for specific creature classes. I define one such class, Orc. Then, I instantiate an Orc object and call a member function to get the orc to grunt hello and another member function to display the orc’s health. Figure 10.5 shows the results of the program.
Using Abstract Classes 353
Figure 10.5
The orc is an object instantiated from a class derived from an abstract class for all creatures.
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 10 folder; the filename is abstract_creature.cpp.
//Abstract Creature
//Demonstrates abstract classes
#include <iostream> using namespace std;
class Creature //abstract class
{
public:
Creature(int health = 100);
virtual void Greet() const = 0; //pure virtual member function virtual void DisplayHealth() const;
protected:
int m_Health;
};
Creature::Creature(int health): m_Health(health)
354 Chapter 10 n Inheritance and Polymorphism: Blackjack
{}
void Creature::DisplayHealth() const
{
cout << "Health: " << m_Health << endl;
}
class Orc : public Creature
{
public:
Orc(int health = 120); virtual void Greet() const;
};
Orc::Orc(int health): Creature(health)
{}
void Orc::Greet() const
{
cout << "The orc grunts hello.\n";
}
int main()
{
Creature* pCreature = new Orc(); pCreature->Greet();
pCreature->DisplayHealth();
return 0;
}