Abstract Classes And Pure Virtual Functions

Pure Virtual Function

Pure Virtual Function are virtual functions that are assigned value of zero. They make for the characteristics of the abstract classes.

Abstract Class

Abstract Class is a class which contains at least one pure virtual function in it.

Syntax:

Due to the virtual functions in the abstract class:

  • Instances of abstract classes cannot be created.
  • If the child of abstract class doesn't extend all pure virtual functions in the parent, then instances of the child class cannot be created.

Let's look at the following example:

Couple of things to notice:

  • Both classes Car and Truck extend class Vehicle.
  • If we uncomment lines 33 and 34 the the code won't compile. That's because objects of those classes cannot be created.
  • If Truck class overwrites the pure virtual function from the parent class (like in the Car class), then Truck object can be created (by uncommenting line 34).