Pure virtual functions let you create a blueprint for other classes. They make sure certain functions are always defined in child classes.
Pure virtual functions in C++
class ClassName { public: virtual ReturnType FunctionName(Parameters) = 0; };
The = 0 means the function is pure virtual.
Classes with pure virtual functions are called abstract classes and cannot be instantiated.
sound in class Animal.class Animal { public: virtual void sound() = 0; // pure virtual function };
area is a pure virtual function that child classes must implement.class Shape { public: virtual double area() const = 0; };
class Vehicle { public: virtual void start() = 0; virtual void stop() = 0; };
This program shows a base class Animal with a pure virtual function sound. The classes Dog and Cat provide their own versions of sound. When we call sound on each, it prints their unique sounds.
#include <iostream> using namespace std; class Animal { public: virtual void sound() = 0; // pure virtual function }; class Dog : public Animal { public: void sound() override { cout << "Woof!" << endl; } }; class Cat : public Animal { public: void sound() override { cout << "Meow!" << endl; } }; int main() { Dog dog; Cat cat; dog.sound(); cat.sound(); return 0; }
You cannot create an object of a class with pure virtual functions directly.
Child classes must override all pure virtual functions to be instantiable.
Pure virtual functions help create flexible and extendable code designs.
Pure virtual functions create a contract for child classes to follow.
They make a class abstract, so you cannot make objects from it.
Child classes must provide their own implementation of pure virtual functions.