Polymorphism: Virtual Functions and Abstract Classes
Polymorphism lets you write code that operates on base class pointers while executing the specialized behavior of derived classes at runtime.
What is it?
Runtime polymorphism in C++ is achieved using `virtual` functions and base class pointers/references. An abstract class has at least one pure virtual function (`virtual void func() = 0;`).
Why is it used?
Enables extensible plugin architectures, game entity rendering, and clean separation between interfaces and implementations.
Detailed Explanation
Syntax Structure
class Base {
public:
virtual void execute() = 0; // Pure virtual (Abstract interface)
virtual ~Base() {} // Virtual destructor mandatory
};
Code Example
#include <iostream>
#include <vector>
#include <memory>
// Abstract Base Interface
class PaymentMethod {
public:
virtual void process_payment(double amount) const = 0; // Pure virtual
virtual ~PaymentMethod() {} // Virtual destructor
};
// Concrete Class 1: UPI
class UPIPayment : public PaymentMethod {
public:
void process_payment(double amount) const override {
std::cout << "[UPI] Processing instantaneous payment of ₹" << amount << " via NPCI Gateway.\n";
}
};
// Concrete Class 2: Card
class CardPayment : public PaymentMethod {
public:
void process_payment(double amount) const override {
std::cout << "[CARD] Authorizing secure 3D-Secure payment of ₹" << amount << " via Visa/MasterCard.\n";
}
};
int main() {
std::cout << "=== Runtime Polymorphism: Payment Processor ===\n";
// Vector of base interface pointers
std::vector<std::unique_ptr<PaymentMethod>> payments;
payments.push_back(std::make_unique<UPIPayment>());
payments.push_back(std::make_unique<CardPayment>());
// Polymorphic execution: Same interface call, different specialized behavior!
for (const auto &payment : payments) {
payment->process_payment(2500.0);
}
return 0;
}
Explanation of the Code
Expected Output
Real-World Application
Used in game engines (where `render()` is called on a list of `GameObject*` containing players, trees, and enemies).
Common Mistakes to Avoid
Quick Practice Challenge
Create an abstract `Shape` class with a pure virtual `double area()` method and a `Circle` implementation.