Learn C++
#include "oopadvanced/overriding.hpp"

Overriding, override & final in C++

//concept

Overriding replaces an inherited virtual function with a derived version of matching signature. The override specifier makes the intent compiler-checked: a typo'd name or mismatched const silently creates a new hiding function without it, but with override the compiler errors instead of misbehaving.

final closes the door from the other side — a final class can't be inherited, a final virtual can't be overridden further. Together they document design intent (this hierarchy ends here) and occasionally help the optimizer devirtualize calls.

//how it works
1

Match the signature exactly

Same name, same parameters, same constness — any deviation hides the base function instead of overriding it.

2

Always write override

void speak() override; asks the compiler to verify a matching base virtual exists — signature drift becomes a loud error.

3

final seals hierarchies

class Engine final blocks all inheritance; void run() final blocks further overriding — use sparingly, where extension is genuinely wrong.

4

Covariant returns allowed

An override may return a derived-class pointer/reference where the base returns a base one — the one legal signature difference.

//example
#include <iostream>
 
class Base {
public:
virtual void run() { std::cout << "base" << std::endl; }
virtual ~Base() = default;
};
 
class Child : public Base {
public:
void run() override { std::cout << "child" << std::endl; }
};
 
int main() {
Base* p = new Child();
p->run();
delete p;
return 0;
}
Output
child
1Child::run matches Base::run exactly and carries override, so the compiler verified the relationship.
2Through the Base* pointer, virtual dispatch selects the Child body at run time.
3child prints — the override won over the base implementation.
//use cases
Catching signature typos at compile time with mandatory override in code review
Sealing security-sensitive or performance-critical classes with final
Evolving base classes safely: added virtuals can't silently hijack derived names when override is enforced
Documenting which classes are extension points and which are closed

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.