C++:C++ Inheritance, Virtual Functions, and Polymorphism
C++•Inheritance

C++ Inheritance, Virtual Functions, and Polymorphism

Master polymorphic class hierarchies in C++ using virtual functions, override keyword, and virtual destructors.

Syntax

class Derived : public Base { void execute() override; };

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
virtualKeywordEnables dynamic dispatch via vtable.
overrideSpecifierVerifies method signature matches virtual base method.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

#include <iostream>
#include <vector>
#include <memory>
#include <string>

// Base Class with pure virtual function (Abstract Class)
class StorageDriver {
public:
    virtual ~StorageDriver() = default; // Essential virtual destructor
    virtual void save(const std::string& record) = 0; // Pure virtual
};

class S3Driver : public StorageDriver {
public:
    void save(const std::string& record) override {
        std::cout << "[S3-Bucket] Persisted: " << record << "\n";
    }
};

class LocalDiskDriver : public StorageDriver {
public:
    void save(const std::string& record) override {
        std::cout << "[Local-NVMe] Written to /data/: " << record << "\n";
    }
};

int main() {
    std::vector<std::unique_ptr<StorageDriver>> drivers;
    drivers.push_back(std::make_unique<S3Driver>());
    drivers.push_back(std::make_unique<LocalDiskDriver>());

    for (const auto& driver : drivers) {
        driver->save("Snapshot_2026_Q4.tar.gz");
    }

    return 0;
}
Expected Output:
[S3-Bucket] Persisted: Snapshot_2026_Q4.tar.gz
[Local-NVMe] Written to /data/: Snapshot_2026_Q4.tar.gz

How It Works: Step-by-Step

  • Lines 7-11: Defines abstract base class with virtual destructor and pure virtual method.
  • Lines 13-25: Concrete subclasses implement override method save().
  • Lines 28-34: Polymorphic dispatch using smart pointers std::unique_ptr.

Key Concepts

  • A class with at least one pure virtual function (= 0) is an abstract class.
  • Base classes intended for polymorphic deletion MUST declare a virtual destructor.
  • Use override keyword to catch typos in method signatures at compile time.

Common Mistake: Deleting a derived class through a base pointer without a virtual destructor

Omitting virtual ~Base() leads to undefined behavior and memory leaks when deleting derived objects.

❌ Incorrect
class Base { ~Base() {} }; // Missing virtual destructor!
✅ Correct
class Base { virtual ~Base() = default; }; // Safe polymorphic cleanup

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler