bhylu.com

Advertisements

C++ Polymorphism

Use an abstract base with a virtual destructor and invoke two independently defined implementations.

How it works

Runtime polymorphism lets code call a common interface while the concrete object chooses the implementation. A pure virtual function describes a required operation; override asks the compiler to verify that a derived declaration really overrides it. If objects may be destroyed through a base pointer, the base needs a virtual destructor. Prefer a small interface with a clear semantic contract. Inheritance is not required for every variation; composition, templates or a callable can be simpler.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror polymorphism.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · polymorphism.cpp

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

class Estimate {
public:
    virtual int minutes() const = 0;
    virtual ~Estimate() = default;
};
class Walking final : public Estimate {
public: int minutes() const override { return 40; }
};
class Cycling final : public Estimate {
public: int minutes() const override { return 18; }
};

int main() {
    std::vector<std::unique_ptr<Estimate>> policies;
    policies.push_back(std::make_unique<Walking>());
    policies.push_back(std::make_unique<Cycling>());
    for (const auto& policy : policies) { std::cout << policy->minutes() << " minutes\n"; }
}

Expected result

40 minutes
18 minutes

The owning pointers avoid slicing derived objects into base values. Destruction through each base pointer reaches the derived destructor. The constants isolate dispatch; a real estimate would require distance, traffic and a documented model. protected can expose selected base functionality to derived implementations, while public defines the caller interface. Keep data private unless a clear extension contract needs more access.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.