What is pure virtual function in C++? Give example when it is used

(Last Updated On: February 25, 2019)

Answer includes what is pure virtual function in C++ with simple code example and uses of it in creating interfaces and abstract class in C++ programming.

Answer: Pure virtual function in C++ object oriented programming is a virtual function with the expression “ = 0” appended to the function declaration. E.g. virtual void func() = 0;

 

We can write pure virtual functions in a class as below. Pure virtual function should not have implementation in the class itself and all pure virtual functions must be defined or have to be implemented in all derived classes.

In above example, if we derive a class from Animal base class then derived class will be forced to implement all functions. if we miss even a single pure virtual function to implement in child class then on object creation compiler will throw an error.

For example in below program, we have not implemented eat() pure virtual function, So, when we create the object of Dog class compiler will complain that can not instantiate abstract class. Once we implement all function it should be OK.

 

NOTE
Virtual function in C++ object oriented programming is different than pure virtual function. Virtual functions have definition in base class and compiler don’t complain if we don’t override it.

Pure virtual functions are used to create an interface in c++ or an abstract class in C++ with simple example . There is no keyword like interface or abstract class in C++ language. So, pure virtual function is used to create an interface class and an abstract class in C++ programs.

Important points about c++ pure virtual function
  • If a class contains at least one pure virtual function then it will be called an abstract class that cannot be instantiated. Means, we cannot create object of this class.
  • There is no c++ pure virtual constructor concept.

 

NOTES:

  • We cannot create the object of an abstract class but we can create the pointer of this class and assign the object of derived classes.
  • Derived classes must implement the pure virtual functions or else compiler will flash an error at compile time itself.