Pure Virtual Functions and Abstract Classes in C++



C++ Pure Virtual Functions

A pure virtual function in C++ is a virtual function that has no definition in the base class and must be overridden in derived classes. It is declared by assigning = 0 in its declaration.

Syntax

Following is the syntax of the pure virtual function:

class Shape {
public:
   virtual double area() = 0;
};

C++ Abstract Class

A class that contains at least one pure virtual function is called an abstract class. Abstract classes cannot instantiated directly; instead, they work as a blueprint of the derived class.

Any class inheriting from an abstract class must provide an implementation for all pure virtual functions it inherits unless it too is declared abstract.

  • 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.

  • If an Abstract Class has derived class, they must implement all pure virtual functions, or else they will become Abstract too.

  • We can't create object of abstract class as we reserve a slot for a pure virtual function in Vtable, but we don't put any address, so Vtable will remain incomplete.

Example: Runtime Polymorphism using a Pure Virtual Function

This example implements runtime polymorphism using a pure virtual function and dynamic binding:

#include<iostream>
using namespace std;
class B {
   public:
      virtual void s() = 0;
};

class D:public B {
   public:
      void s() {
         cout << "Virtual Function in Derived class\n";
      }
};
int main() {
   B *b;
   D dobj;
   b = &dobj;
   b->s();
}

The above code generates the following output:

Virtual Function in Derived class

Example: Abstract Class with a Pure Virtual Function

In this example, we implement an abstract class with a pure virtual function:

#include <iostream>
using namespace std;
class Shape {
   public: virtual void draw() = 0;
};

class Circle: public Shape {
   public: void draw() override {
      cout << "Drawing a Circle" << endl;
   }
};

class Rectangle: public Shape {
   public: void draw() override {
      cout << "Drawing a Rectangle" << endl;
   }
};

int main() {
   Shape * shape1;
   Circle circleObj;
   Rectangle rectObj;

   shape1 = & circleObj;
   shape1 -> draw();

   shape1 = & rectObj;
   shape1 -> draw();

   return 0;
}

Following is the output of the above code:

Drawing a Circle
Drawing a Rectangle
Updated on: 2025-05-28T16:47:25+05:30

25K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements