Lesson 23 of 45
C++Lesson 23: Polymorphism and Virtual Functions
12 min
Course progress51%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 23 of 45
C++12 min
Keep these ideas in mind as you work through the lesson.
Polymorphism enables a base‑class pointer or reference to invoke derived‑class behaviour at runtime. This is achieved through virtual functions and a hidden v‑table.
Animal hierarchyclass Animal {
public:
virtual void speak() const = 0; // pure virtual
virtual ~Animal() = default;
};
class Dog : public Animal {
public:
void speak() const override { std::cout << \"Woof!\
\"; }
};
class Cat : public Animal {
public:
void speak() const override { std::cout << \"Meow!\
\"; }
};
int main() {
std::vector<std::unique_ptr<Animal>> zoo;
zoo.emplace_back(std::make_unique<Dog>());
zoo.emplace_back(std::make_unique<Cat>());
for (const auto& a : zoo) {
a->speak(); // calls the correct derived implementation
}
return 0;
}
Key points:
final can prevent further overriding.Tip: Prefer non‑virtual functions for performance‑critical code. Use
overrideto catch mistakes.
<Alert type="warning">Calling a virtual function from a base class constructor or destructor does not dispatch to the derived implementation.