< Previous | Contents | Next >

Declaring Pure Virtual Functions

A pure virtual function is one to which you dont need to give a definition. The logic behind this is that there might not be a good definition in the class for the member function. For example, I dont think it makes sense to define the Greet() function in my Creature class because a greeting really depends on the specific type of creaturea pixie twinkles, a dragon blows a puff of smoke, and an orc grunts.

Using Abstract Classes 355


You specify a pure virtual function by placing an equal sign and a zero at the end of the function header. Thats what I did in Creature with the following line:

virtual void Greet() const = 0; //pure virtual member function

When a class contains at least one pure virtual function, its an abstract class. Therefore, Creature is an abstract class. I can use it as the base class for other classes, but I cant instantiate objects from it.

An abstract class can have data members and virtual functions that are not pure virtual. In Creature, I declare a data member m_Health and a virtual member function DisplayHealth().