pure virtual function:

  • A pure virtual function means „do nothing‟ function.
  • We can say empty function. A pure virtual function has no definition relative to the base class.
  • Programmers have to redefine pure virtual function in derived class, because it has no definition in base class.
  • A class containing pure virtual function cannot be used to create any direct objects of its own.
  • This type of class is also called as abstract class.

Syntax:

virtual void display() = 0; OR virtual void display()

{

}

abstract class with Example:

Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must provide definition to the pure virtual function, otherwise they will also become abstract class.

Characteristics of Abstract Class

  • Abstract class cannot be instantiated, but pointers and refrences of Abstract class type can be created.
  • Abstract class can have normal functions and variables along with a pure virtual function.
  • Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
  • Classes inheriting an Abstract Class must implement all pure virtual functions, or else they will become Abstract too.

Example:

class Base          //Abstract base class
{
    public:
    virtual void show() = 0;            //Pure Virtual Function
};

class Derived:public Base
{
    public:
 
    void show()
    {
        cout << "Implementation of Virtual Function in Derived class";
    }
};

int main()
{
    Base obj;       //Compile Time Error
    Base *b;
    Derived d;
    b = &d;
    b->show();
}