Pure Virtual Functions in C++: Creating Abstract Interfaces
What is Pure Virtual Functions in C++: Creating Abstract Interfaces? A pure virtual function is a virtual function declared with = 0 (virtual void render() = 0;) that must be overridden by concrete derived classes. A class with a...
What are pure virtual functions, how do they create abstract classes, and can a pure virtual function have an implementation?
Explanation & In-Depth Details
```text
┌─────────────────────────────────┐
│ <<Abstract>> IStorage │
├─────────────────────────────────┤
│ + saveRecord(data): bool = 0 │ ◄── Pure Virtual Contract
│ + readRecord(id): string = 0 │
└────────────────┬────────────────┘
│
┌─────────┴─────────┐
▼ ▼
┌──────────────┐ ┌──────────────┐
│ SqlStorage │ │ RedisStorage │
└──────────────┘ └──────────────┘
```
2. Pure Virtual with Body:
Useful for providing default cleanup logic in a pure virtual base destructor (`virtual ~Base() = 0;`).
Code Example
#include <iostream>
#include <memory>
#include <vector>
// Abstract Base Class / Interface
class IPaymentGateway {
public:
virtual ~IPaymentGateway() = default;
// Pure Virtual Function
virtual bool processPayment(double amount) = 0;
};
class StripeGateway : public IPaymentGateway {
public:
bool processPayment(double amount) override {
std::cout << "[Stripe API] Successfully charged $" << amount << "\n";
return true;
}
};
class PayPalGateway : public IPaymentGateway {
public:
bool processPayment(double amount) override {
std::cout << "[PayPal API] Successfully routed $" << amount << "\n";
return true;
}
};
int main() {
std::vector<std::unique_ptr<IPaymentGateway>> gateways;
gateways.push_back(std::make_unique<StripeGateway>());
gateways.push_back(std::make_unique<PayPalGateway>());
for (const auto& gw : gateways) {
gw->processPayment(49.99);
}
return 0;
}Interview Question & Tips
A: No. If a derived class does not override all pure virtual functions, it remains an abstract class itself and cannot be instantiated.
Q: Why would you ever define a body for a pure virtual function in C++?
A: To provide common reusable default behavior that derived classes can explicitly call (e.g. `Base::process()`) or to make a class abstract by declaring its destructor pure virtual (`virtual ~Base() = 0;`).
Best Practices
• Keep interfaces focused and granular according to the Interface Segregation Principle (ISP).
• Always mark overrides in derived classes with `override` to ensure exact signature matching.
This study reference for Pure Virtual Functions in C++: Creating Abstract Interfaces is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation: