final and override with an example in C++ โ OOP-Friendly Keywords (Introduced in C++11)
If you’re familiar with Object-Oriented Programming (OOP), the final and override specifiers in C++11 make inheritance and polymorphism safer and clearer.
๐ท 1. Override Ensure You’re Overriding a Virtual Function
override is used to explicitly mark that a method is overriding a virtual method from a base class. If the base class doesn’t have a virtual method with the same signature, the compiler will generate an error.
๐ธ Example: Without override (Risky)
class Base {
public:
virtual void speak() const {
std::cout << "Base speaking\n";
}
};
class Derived : public Base {
public:
void speak() { // ๐ Not overriding due to missing `const`
std::cout << "Derived speaking\n";
}
};
No compile-time error, but polymorphism fails silently.
โ With override
class Derived : public Base {
public:
void speak() const override { // โ
compiler checks base method
std::cout << "Derived speaking\n";
}
};
If you mistype or mismatch the signature, the compiler catches it.
๐ท 2. final โ Prevent Further Overriding or Inheritance
final can be used in two ways:
- On a class: prevents any class from inheriting it.
- On a virtual method: prevents it from being overridden again.
๐ธ final on a Class
class Sealed final {
public:
void display() {}
};
// class Child : public Sealed {}; โ Compile-time error
๐ธ final on a Method
class A {
public:
virtual void foo() final {
std::cout << "A::foo\n";
}
};
class B : public A {
// void foo() override; โ Error: foo is final in A
};