Skip to main content

Pure virtual function and abstract class

Short answer

A pure virtual function (declared with = 0) has no implementation in base, making the class abstract (non-instantiable). Overriding it in derived classes enables run-time polymorphism: a base pointer calls the derived function, determined dynamicly at program execution.

What is pure virtual function and abstract class? With suitable example explain run time polymorphism.

Pure virtual function

A pure virtual function is a virtual function with no body in the base class. It is declared by writing = 0:

virtual void draw() = 0;

It forces every non-abstract derived class to provide its own definition.

Abstract class

A class that has at least one pure virtual function is an abstract class. Objects of an abstract class cannot be created, but pointers and references to it can be. It is used as a base class that defines an interface. A derived class that does not override all pure virtual functions is also abstract.

Run-time polymorphism

It means the function to be called is decided at run time from the actual type of the object that the base pointer points to. It needs (a) inheritance, (b) a virtual function overridden in the derived class, (c) a base class pointer or reference.

#include <iostream>
using namespace std;

class Shape {                               // abstract class
public:
    virtual void area() = 0;                // pure virtual function
};

class Circle : public Shape {
    float r;
public:
    Circle(float x) { r = x; }
    void area() { cout << "Circle area = " << 3.14159 * r * r << endl; }
};

class Rect : public Shape {
    float l, b;
public:
    Rect(float x, float y) { l = x; b = y; }
    void area() { cout << "Rectangle area = " << l * b << endl; }
};

int main() {
    // Shape s;                // error: cannot create abstract object
    Shape *p;
    Circle c(2);
    Rect r(3, 4);

    p = &c;  p->area();        // Circle::area  (decided at run time)
    p = &r;  p->area();        // Rect::area
    return 0;
}

Output:

Circle area = 12.5664
Rectangle area = 12

The same call p->area() runs different code depending on the object p points to. This is run-time polymorphism (dynamic binding), implemented through the virtual table (vtable).

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 7 questions →