Overriding in one sentence
Function overriding happens when a derived class provides its own version of a member function that the base class marks virtual. A call through a base class pointer or reference then runs the derived version.
A working example
#include <iostream>
class Animal {
public:
virtual void speak() const {
std::cout << "...\n";
}
virtual ~Animal() = default;
};
class Dog : public Animal {
public:
void speak() const override {
std::cout << "Woof\n";
}
};
int main() {
Dog dog;
Animal* pet = &dog;
pet->speak(); // prints Woof
}
Dog::speak has the same name, the same (empty) parameter list, and the same const qualifier as Animal::speak, so it overrides the base version. The override keyword asks the compiler to confirm that. The call goes through an Animal*, but the object is a Dog, so the Dog version runs.
The virtual destructor in Animal follows the same logic. It makes sure that deleting a Dog through an Animal* cleans up correctly.
Why virtual matters
Without virtual in Animal, pet->speak() calls Animal::speak, because the compiler uses the pointer’s type to pick the function. The speak in Dog would then be a separate function that hides the base version. It would not be an override.
Overriding vs. overloading
| Overloading | Overriding | |
|---|---|---|
| Where it happens | Functions in the same scope | A base class and a derived class |
| Parameter list | Must differ | Must match |
| When the version is chosen | At compile time | At runtime, for virtual functions |
| Keywords | None needed | virtual in the base class, and override in the derived class |
Overloading is the subject of what is function overloading, and the two are often mixed up because both reuse a name.
Common mistakes
- Forgetting
virtualin the base class. The derived function then hides the base one, and calls through base pointers use the base version. - Mismatched signatures. A derived
void speak()withoutconstdoesn’t override a basevoid speak() const. Withoverride, the compiler reports an error, which makes the mistake easy to catch. - Leaving out
override. Without it, the same mismatch compiles quietly, and the bug can go unnoticed.
Where overriding fits
Overriding is a main way C++ achieves runtime polymorphism, which is one part of polymorphism in C++. It depends on inheritance in C++, where a derived class is built on a base class. Keep it separate from overloading, which picks a version at compile time based on the arguments.
Key takeaways
- Overriding replaces a
virtualfunction from a base class in a derived class. - The signature has to match, and
overridelets the compiler check it. - The version that runs is chosen at runtime, based on the object’s actual type.
- Overloading is a different idea: it chooses among functions with the same name at compile time.