Pure Virtual Functions

A pure virtual function is similar to a virtual function, in that it is used when you expect a class to be the object of derivation. However, when you declare a pure virtual function in a class, you are saying that this particular class can never be instantiated and that its purpose is to serve as a placeholder in the class. In addition, a function that is declare to be pure virtual cannot be defined. Any class with one or more virtual functions is referred to as an abstract class.

virtual void draw( ) = 0;

Notice that the declaration is initialized to zero.

It is important to realize that if an abstract class with a pure virtual function is inherited, then the inheriting class will also be abstract (and therefore cannot be instantiated) or the function must be defined.

Why would you want to declare a pure virtual function? The answer is -- design. Remember, object-oriented programming is about modelling, not just software, but systems. So, back to the question, why would anyone want a class that couldn't be instantiated? Stroustrup says, "An important use of abstract classes is to provide an interface without exposing any implementation details. (p.192)" Let's take the famous car example. We may want to create a base class called car, but we certainly wouldn't want to implement it. The car would have an engine, doors, and tires. But we don't know what kind of engine, or how many doors, or what tires will fit on the rims. We know we need these things, but we are going to leave the implementation to the derived classes. So, why not simply declare and define all these things in each derived car class that we need to create? By doing this, it would be the responsibility of each class and subclass (i.e., class Volkswagon, class Jetta : public Volkswagon...) to declare and define every bit of functionality that it needs. You might think that you have to do this anyways. Chances are, however, that it will be possible to implement some functionality in each of the parent (base) classes so that you won't, say, have to design the fuel injectors (which may be the same on a number of models) each time you create a new car class. Moreover, pure virtual functions in a base class can prevent a future class implementor from forgetting to include some very important function (like airbags). Let's say a designer has included airbags as a pure virtual function in the class Volkswagon. Now, when some class designer wants to create a new Jetta, should she forget to define the airbag member function in her new class, she will not be able to instantiate it (the compiler will give you an error). So, pure virtual functions, like airbags, exist for your safety.

1