IntermediateLesson 10 of 18
Inheritance, virtual and Polymorphism – C++
Base classes, virtual methods, abstract classes and the slicing trap.
A derived class inherits members of the base class. With virtual in the base and override in the derived class, the appropriate method is chosen at runtime (dynamic binding) – that is polymorphism.
#include <iostream>
#include <memory>
#include <string>
#include <utility>
#include <vector>
class Tier {
public:
explicit Tier(std::string name) : name_(std::move(name)) {}
virtual ~Tier() = default; // virtual destructor!
virtual std::string sprich() const { return name_ + " makes a sound"; }
protected:
std::string name_;
};
class Hund : public Tier {
public:
using Tier::Tier; // inherit constructors
std::string sprich() const override { return name_ + " says Woof!"; }
};
int main() {
std::vector<std::unique_ptr<Tier>> tiere;
tiere.push_back(std::make_unique<Tier>("Something"));
tiere.push_back(std::make_unique<Hund>("Rex"));
for (const auto& t : tiere) std::cout << t->sprich() << '\n';
}An abstract class has at least one pure virtual method (= 0) and cannot be instantiated. It defines an interface:
class Form {
public:
virtual ~Form() = default;
virtual double flaeche() const = 0;
};
class Kreis : public Form {
public:
explicit Kreis(double r) : r_(r) {}
double flaeche() const override { return 3.14159265 * r_ * r_; }
private:
double r_;
};virtual ~Basis() = default;– mandatory as soon as you delete through a base pointer (otherwise UB)override– the compiler checks that a virtual method is really being overriddenfinal– forbids further overriding or deriving- Polymorphism only works through pointers or references, not through values
WarningSlicing: if you copy a
Hund object into a Tier variable (Tier t = hund;), the Hund part is cut off – a plain Tier remains, and t.sprich() returns the Tier version. So always pass polymorphic objects by reference, pointer or smart pointer.TipPrefer composition over inheritance: "has a" instead of "is a". Inheritance is mainly worthwhile for interfaces and genuine polymorphism.