Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / C++ Programming Tutorial / Chapter 3: Object-Oriented Programming (OOP) in C++
CPP ⏱ 14 min read

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

How Virtual Functions Work: • Static Binding (default): Function call resolved at compile time based on pointer type. • Dynamic Binding (`virtual`): Function resolved at runtime based on the actual object being pointed to via a virtual method table (vtable). • `override` keyword (C++11): Informs compiler that method overrides a base virtual method, catching signature typos. • Virtual Destructor: Always make base class destructors `virtual`! Without a virtual destructor, deleting a derived object through a base pointer causes memory leaks.

Syntax Structure

Syntax Blueprint
class Base {
public:
    virtual void execute() = 0; // Pure virtual (Abstract interface)
    virtual ~Base() {}          // Virtual destructor mandatory
};

Code Example

CPP Code
#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

• `virtual void process_payment(...) = 0` creates an abstract contract interface. • `std::vector<std::unique_ptr<PaymentMethod>>` stores pointers to derived payment classes. • The loop executes specialized UPI or Card logic dynamically at runtime.

Expected Output

=== Runtime Polymorphism: Payment Processor === [UPI] Processing instantaneous payment of ₹2500 via NPCI Gateway. [CARD] Authorizing secure 3D-Secure payment of ₹2500 via Visa/MasterCard.

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

• Forgetting `virtual ~Base() {}` in the base class, leading to partial destruction and memory leaks. • Forgetting the `override` keyword on derived methods (typos like `process_paymnt` silently fail to override).

Quick Practice Challenge

Create an abstract `Shape` class with a pure virtual `double area()` method and a `Circle` implementation.

Key Takeaways

• Use `virtual` for runtime dynamic dispatch via vtable. • Classes with pure virtual functions (`= 0`) are Abstract Classes. • Always declare base class destructors as `virtual`.