In C++, a pure virtual function is a function that has no implementation within the base class. It is declared using the “virtual” keyword followed by “= 0” in its declaration. The purpose of a pure virtual function is to define an interface that must be implemented by derived classes. It serves as a placeholder for the derived classes to provide their own implementation.
Here’s an example to illustrate the usage of pure virtual functions in C++:
#include <iostream>
class Animal {
public:
virtual void makeSound() const = 0; // Pure virtual function
void sleep() {
std::cout << "Zzz..." << std::endl;
}
};
class Dog : public Animal {
public:
void makeSound() const override {
std::cout << "Woof!" << std::endl;
}
};
class Cat : public Animal {
public:
void makeSound() const override {
std::cout << "Meow!" << std::endl;
}
};
int main() {
Dog dog;
Cat cat;
dog.makeSound(); // Outputs "Woof!"
cat.makeSound(); // Outputs "Meow!"
dog.sleep(); // Outputs "Zzz..."
cat.sleep(); // Outputs "Zzz..."
return 0;
}
In this example, the Animal
class is an abstract base class with a pure virtual function makeSound()
. This function doesn’t have an implementation in the base class because each derived class (e.g., Dog
, Cat
) should provide its own implementation of makeSound()
. The Animal
class also has a non-virtual function sleep()
that is inherited by the derived classes.
The Dog
and Cat
classes inherit from the Animal
class and override the makeSound()
function with their specific sound implementations.
Note that because the Animal
class has a pure virtual function, it cannot be instantiated directly. It can only be used as a base class for derived classes, which must override the pure virtual function to provide their own implementation.