Pure virtual functions have a few key use cases:
Pure virtual functions ensure that derived classes implement specific functions.
This enforces a contract, making it clear what functionality must be provided by any class that inherits from the base class.
They allow you to define a common interface for a set of classes without providing a specific implementation in the base class.
This gives derived classes the flexibility to implement the details.
Abstract classes can contain non-virtual functions that provide common functionality, while pure virtual functions define the interface.
This helps in keeping the shared code centralized and reduces duplication.
Pure virtual functions enable polymorphic behavior, allowing you to write code that can operate on a base class reference or pointer but execute derived class methods.
Here’s an example to illustrate the use of pure virtual functions:
#include <iostream>
#include <string>
// Abstract base class with a pure virtual function
class Animal {
public:
virtual void MakeSound() = 0;
};
class Dog : public Animal {
public:
void MakeSound() override {
std::cout << "Bark!\n";
}
};
class Cat : public Animal {
public:
void MakeSound() override {
std::cout << "Meow!\n";
}
};
int main() {
Dog dog;
Cat cat;
dog.MakeSound();
cat.MakeSound();
}
Bark!
Meow!
In this example:
Animal
is an abstract class with a pure virtual function MakeSound()
.Dog
and Cat
provide implementations for the MakeSound()
function, enforcing the contract.Pure virtual functions are a powerful feature in C++ that help enforce design contracts, enable polymorphism, and provide design flexibility, despite their complexity.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create interfaces and abstract classes using pure virtual functions