Override & Final
Keywords in C++
Master the override and final keywords to write safer virtual functions, catch bugs at compile time, and control class inheritance.
Quick Recap: Virtual Functions
In C++, a virtual function in a base class can be overridden in a derived class. When you call it through a base-class pointer, the derived version runs. This is runtime polymorphism.
The Silent Bug Problem
Without override, a small typo means you create a new function instead of overriding. The compiler says nothing. The bug hides until runtime.
Enter the override Keyword
C++11 introduced override: a specifier you place after the function declaration. It tells the compiler: "I intend to override a base-class virtual function."
How override Works
The final Keyword
final does the opposite job: it prevents further overriding of a virtual function, or prevents a class from being inherited at all.
final in Practice
override vs final
| override | final | |
|---|---|---|
| Purpose | Confirm you are overriding | Prevent further overriding |
| Applies to | Virtual member functions | Functions or entire classes |
| When it fires | Signature mismatch with base | Any attempt to override / inherit |
| Introduced in | C++11 | C++11 |
| Can be combined? | Yes: override final | |
Visualizing the Hierarchy
Why Use Them?
Step-by-Step Checklist
Example 1: Basic Override
Example 2: override + final
Example 3: final on a Class
Common Mistakes
Summary Cheat Sheet
| Syntax | Meaning | Error If... |
|---|---|---|
void f() override; |
I'm overriding a base virtual | No matching virtual in base |
void f() final; |
No subclass may override f() | A subclass tries to override f() |
void f() override final; |
I'm overriding + locking it | Either condition fails |
class C final { }; |
No class may inherit from C | Any class tries to derive from C |
Question 1 of 5
What happens if you write override on a function whose signature does not match any virtual function in the base class?
Question 2 of 5
Which of the following correctly uses final to prevent a class from being inherited?
Question 3 of 5
class Base {
public:
virtual void process() const;
};
class Derived : public Base {
public:
void process() override;
};
Will the code above compile? If not, why?
Question 4 of 5
If a function is marked override final in class Middle, which of the following is true?
Question 5 of 5
What is one practical performance benefit of marking a virtual function as final?