0
0
CppConceptBeginner · 3 min read

What is Pure Virtual Function in C++: Definition and Usage

A pure virtual function in C++ is a function declared in a base class with = 0 that has no implementation there. It forces derived classes to provide their own version, making the base class abstract and uninstantiable.
⚙️

How It Works

Think of a pure virtual function as a promise in a blueprint. The base class says, "Any class that follows me must have this function," but it doesn't say how it works. This means the base class cannot create objects on its own because it has incomplete parts.

Derived classes must fulfill this promise by writing their own version of the function. This design helps create a common interface while allowing different behaviors in each derived class, like different types of vehicles all having a startEngine() function but each starting differently.

💻

Example

This example shows a base class with a pure virtual function and two derived classes implementing it differently.

cpp
#include <iostream>
using namespace std;

class Animal {
public:
    virtual void sound() = 0; // pure virtual function
};

class Dog : public Animal {
public:
    void sound() override {
        cout << "Dog barks" << endl;
    }
};

class Cat : public Animal {
public:
    void sound() override {
        cout << "Cat meows" << endl;
    }
};

int main() {
    Dog dog;
    Cat cat;
    Animal* animal1 = &dog;
    Animal* animal2 = &cat;
    animal1->sound();
    animal2->sound();
    return 0;
}
Output
Dog barks Cat meows
🎯

When to Use

Use pure virtual functions when you want to create a base class that defines a common interface but should not be instantiated on its own. This is useful in designs where different subclasses share the same function names but have different implementations.

For example, in a graphics program, you might have a base class Shape with a pure virtual function draw(). Each shape like Circle or Rectangle implements draw() differently. This ensures all shapes can be treated uniformly while drawing themselves uniquely.

Key Points

  • A pure virtual function is declared by assigning = 0 in the base class.
  • It makes the base class abstract, so you cannot create objects of it.
  • Derived classes must override the pure virtual function to be instantiable.
  • It enforces a contract for derived classes to implement specific behavior.

Key Takeaways

A pure virtual function forces derived classes to provide their own implementation.
Declaring a pure virtual function makes the base class abstract and uninstantiable.
Use pure virtual functions to define interfaces that multiple classes share but implement differently.
Derived classes must override all pure virtual functions to create objects.
Pure virtual functions help design flexible and extendable class hierarchies.