Inheritance and Polymorphism
A class can inherit from another with : public Base. Marking a base class method virtual, and the derived class's version override, tells the compiler to dispatch dynamically: when you call the method through a base class pointer or reference, the actual runtime type's version runs — not necessarily the one the static type would suggest.
#include <iostream>
#include <string>
using namespace std;
class Animal {
public:
virtual string speak() const {
return "...";
}
};
class Dog : public Animal {
public:
string speak() const override {
return "Woof!";
}
};
class Cat : public Animal {
public:
string speak() const override {
return "Meow!";
}
};
int main() {
Dog dog;
Cat cat;
Animal* animals[2] = { &dog, &cat };
for (int i = 0; i < 2; i++) {
cout << animals[i]->speak() << endl;
}
return 0;
}Woof! Meow!
animals is an array of Animal* — a statically typed base-class pointer — but each element still calls the correct derived class's speak(). Without virtual, both calls would print '...' instead, since the compiler would resolve the call statically against the declared Animal type rather than dispatching at runtime.
Next: operator overloading — giving your own types the same +, -, == syntax built-in types already have.
Practice exercise
Define a class Shape with a virtual method name() returning "Shape". Define a class Circle that inherits from Shape and overrides name() to return "Circle". Create a Circle through a Shape* pointer and print its name().