C++ override Keyword
Example
Use override to show that a method replaces a virtual method from the parent class:
class Animal {
public:
virtual void animalSound() {
cout << "The animal makes a sound\n";
}
};
class Pig : public Animal {
public:
void animalSound() override {
cout << "The pig says: wee wee\n";
}
};
class Dog : public Animal {
public:
void animalSound() override {
cout << "The dog says: bow wow\n";
}
};
int main() {
Pig myPig;
Dog myDog;
Animal* a1 = &myPig;
Animal* a2 = &myDog;
a1->animalSound();
a2->animalSound();
return 0;
}
Definition and Usage
The override keyword specifies that a method overrides (replaces) a virtual method from the parent class. Write it after the parentheses of the method, like void animalSound() override.
It is optional, but recommended. If the parent class has no virtual method with the same name and parameters, the compiler gives an error. This catches mistakes, like a typo in the method name.
Like final, override is not a reserved word, so you can still use it as a name. It only has a special meaning in a class.
Related Pages
Read more about virtual functions in our C++ Virtual Functions Tutorial.