Polymorphism basics
- C++ course
- Intermediate
- Lesson 36/116
- 5 min
Learn that the same call behaves differently on different types.
Polymorphism basics
Polymorphism lets you call a derived class method through a base class pointer. The base method is marked virtual.
Example: class Animal { public: virtual void speak() { } };. The Dog class inherits from Animal and overrides speak(). With Animal* a = new Dog(); the call a->speak(); runs Dog::speak(). This happens through dynamic dispatch thanks to virtual. The override keyword states the intent to override.
Dynamic dispatch
When a virtual method is called, the compiler looks at the actual type of the pointer to decide which implementation runs. This is known as dynamic dispatch.
If speak() were not virtual, a->speak() through Animal* a = new Dog(); would only run Animal::speak(). With virtual, the most derived implementation is chosen. Writing override is not required but catches errors: a wrong signature gives a compile error.
Practice Define Animal and Dog classes
Define an Animal class with virtual void speak() under public:, body std::cout << "Sound";. A Dog class inherits from Animal; its void speak() override body is std::cout << "Woof";. In main write Animal* a = new Dog();, call a->speak(); and delete a;.
Starter code
#include <iostream>
// Define Animal and Dog classes here
int main() {
// Create a Dog via Animal* and call speak
return 0;
}Sample solution
#include <iostream>
class Animal {
public:
virtual void speak() { std::cout << "Sound"; }
};
class Dog : public Animal {
public:
void speak() override { std::cout << "Woof"; }
};
int main() {
Animal* a = new Dog();
a->speak();
delete a;
return 0;
}Expected output
Woof
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the virtual keyword do?
virtual void speak() { }- Hides the method
- Enables dynamic dispatch Correct answer
- Makes the method private
- Speeds up the method
Explanation: virtual lets a base pointer call the derived implementation.
2 Complete the virtual method declaration
class Animal { public: ____ void speak() { } };
class Animal { public: virtual void speak() { } };
Explanation: virtual enables dynamic dispatch.
3 Match each piece to its role
| Term | Meaning |
|---|---|
virtual |
Dynamic dispatch |
override |
Override |
Animal* |
Base pointer |
->speak() |
Pointer call |