0
0
C++programming~5 mins

Pure virtual functions in C++

Choose your learning style9 modes available
Introduction

Pure virtual functions let you create a blueprint for other classes. They make sure certain functions are always defined in child classes.

When you want to force child classes to provide their own version of a function.
When you are designing a base class that should not be used directly.
When you want to create an interface that many classes can follow.
When you want to share common code but require specific behavior in subclasses.
Syntax
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.

Examples
This declares a pure virtual function sound in class Animal.
C++
class Animal {
public:
    virtual void sound() = 0; // pure virtual function
};
Here, area is a pure virtual function that child classes must implement.
C++
class Shape {
public:
    virtual double area() const = 0;
};
Multiple pure virtual functions can be declared in one class.
C++
class Vehicle {
public:
    virtual void start() = 0;
    virtual void stop() = 0;
};
Sample Program

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.

C++
#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;
}
OutputSuccess
Important Notes

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.

Summary

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.