final and override with an example in C++

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
};