A function with expression = 0 and starting with keyword virtual keyword is called virtual function. The declaration of virtual function is

virtual public void myfoo() = 0;

Uses of pure virtual function

(1) For making abstract class.

A class that is having at least one  pure virtual function is called an abstract class. Like below class Base is an abstract class as it is having expression virtual public void myfoo() = 0;

  • Abstract class cannot be instantiated.

      So, below code will give error at compile time.

#include<iostream>

class Base{
       public:
       // pure virtual, must be implemented by subclasses
       virtual void myfoo() = 0;
};

int main()
{
    Base b;  // will give error because B is abstract
    return 0;
}
  • A pure virtual method or function in Base class must be implemented in Derived class.
#include<iostream>

class Base{
       public:
       // pure virtual, must be implemented by subclasses
       virtual void myfoo() = 0;
};

class Derived: public Base {
       public:
          // definition of myfoo()
          void myfoo(){
           // hello
          };
};
int main()
{
     Derived *d =new Derived();
     return 0;
}

In The above code if we ignore the definition of function myfoo() in Derived class ,the program will not compile.




Related Contents to follow