All About Pure Virtual Functions in C++

In this article, we will discuss pure virtual functions in C++ and usage with examples. Let’s dive into the definition of pure virtual function.

So what is pure virtual function?

A pure virtual function is a function,

  • that must be overriden in the derived class
  • need not to be defined

A virtual function can be declared “pure” using the =0 (pseudo initializer).

Example of pure virtual function declaration

class Base{
   public:
    virtual void f3() =0; //pure virtual function
};

Abstract class and pure virtual function

An abstract class has at least one pure virtual function. We cannot instantiate(create a new object) of an abstract class.

class Base{
   public:
    void f1(); // function
    virtual void f2(); //virtual function
    virtual void f3() =0; //pure virtual function
};

Base b; //  error : pure virtual function f3 not overriden

Here “Base” class is an abstract class because it has a pure virtual function f3. The derived class must override the pure virtual function of the base class.

 class Derived : public Base {
        // no f1: fine
        // no f2: fine, we inherit Base::f2
        void f3();// Overriden pure virtual function
    };
 Derived d; //Ok

Here f3 is overridden hence we can create an object of Derived.

What happens if we don’t override pure virtual function?

If we don’t override pure virtual function in a derived class it will become an abstract class.

class D2 : public Base {
        // no f1: fine
        // no f2: fine, we inherit Base::f2
        // no f3: fine, but D2 is therefore still abstract
    };

 D2 d;   // error: pure virtual Base::f3 not overridden

Here we cannot create an instance of D2 because D2 didn’t override the pure virtual function so it becomes an abstract class.

Conclusion

In conclusion, we can summarize the following points

  • To declare pure virtual function use the “pseudo initializer” =0.
  • A class with one or more pure virtual functions is an abstract class.
  • Pure virtual functions must be overriden by derived class.
  • If we dont override pure virtual function in derived class it will become an abstract class.

Leave a Comment