override
- C++ course
- Intermediate
- Lesson 15/116
- 5 min
Learn to redefine methods with override.
override
Since C++11, a redefined function in a derived class can be marked with the override keyword. This tells the compiler "this function overrides a virtual function in the base class". If the signature does not match, a compile error occurs; this prevents silent bugs.
Example: class Dog : public Animal { public: void speak() override { std::cout << "Woof"; } };. Here override guarantees that speak matches virtual void speak() in the base class. If you accidentally write void speek(), override catches it and gives a compile error, because there is no speek in the base class.
Signature matching
A function marked override must have the same signature as the virtual function in the base class: same name, same parameters, same const-ness. If the signature differs, the compiler errors out. This prevents accidentally creating a new function.
Example: if the base class has virtual int area() const, writing int area() override in the derived class gives a compile error, because const is missing. The correct form is int area() const override. Without override, this difference would silently remain a new function and polymorphism would not work.
Practice Redefine Dog speak with override
Define an Animal class: under public: virtual void speak() { std::cout << "Sound"; }. Derive Dog from Animal and redefine void speak() override { std::cout << "Woof"; }. In main create Dog dog;, take Animal* a = &dog; and call a->speak().
Starter code
#include <iostream>
// Define Animal and Dog classes here
int main() {
// Create Dog, call speak via Animal*
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() {
Dog dog;
Animal* a = &dog;
a->speak();
return 0;
}Expected output
Woof
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each keyword to its role
| Term | Meaning |
|---|---|
virtual |
Makes base function redefinable |
override |
Marks an override in the derived class |
public |
Opens access from outside |
class |
Starts a class definition |
2 Write the override keyword
void speak() ____ { std::cout << "Woof"; }
void speak() override { std::cout << "Woof"; }
Explanation: override states that the base class function is overridden.
3 What is the main benefit of using override?
void speak() override { }- Turns signature mismatch into a compile error Correct answer
- Makes the function private
- Defines a new function
- Makes the function faster
Explanation: override gives a compile error if the signature does not match.