Pure Virtual Member Functions

In this lesson, we'll be learning about a very important concept of polymorphism, i.e., Pure Virtual Member Functions.

Abstract Class

We can only make derived class’s objects to access their functions, and we will never want to instantiate objects of a base class, we call it an abstract class. Such a class exists only to act as a parent of derived classes that will be used to instantiate objects.

How to Write a Pure Virtual Function?

It may also provide an interface for the class hierarchy by placing at least one pure virtual function in the base class. A pure virtual function is one with the expression =0 added to the declaration.

=0 Sign

The equal sign = here has nothing to do with the assignment, the value 0 is not assigned to anything. The =0 syntax is simply how we tell the compiler that a virtual function will be pure.

Overriding Virtual Function

Once you’ve placed a pure virtual function in the base class, you must override it in all the derived classes from which you want to instantiate objects. If a class doesn’t override the pure virtual function, it becomes an abstract class itself, and you can’t instantiate objects from it (although you might from classes derived from it). For consistency, you may want to make all the virtual functions in the base class pure.