C++
override
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.
Exercise 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().
Show example 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;
}
Test yourself
-
Match each keyword to its role
- virtual
- Makes base function redefinable
- override
- Marks an override in the derived class
- public
- Opens access from outside
- class
- Starts a class definition
-
Write the override keyword
void speak() ____ { std::cout << "Woof"; }
Show answer
void speak() override { std::cout << "Woof"; }
-
What is the main benefit of using override?
void speak() override { }
- Turns signature mismatch into a compile error
- Makes the function private
- Defines a new function
- Makes the function faster
Show answer
Turns signature mismatch into a compile error — override gives a compile error if the signature does not match.
Next lesson: Base constructor