Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

override and final in C++

📅 2016-Nov-21 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, final, override, virtual ⬩ 📚 Archive

override and final are two new qualifiers introduced in C++11. The use of these qualifiers is optional. They are meant to be used with virtual methods to show the intention of the method. The compiler uses these qualifiers to check if your intention matches the actual ground truth in your code and throws a compile error if it does not. Thus, it helps to catch bugs earlier at compile time.

This code example shows how to use these qualifiers:

#include <iostream>

// Virtual method declarations

struct A
{
    virtual void Foo() const;
};

struct B : public A
{
    void Foo() const override;
};

struct C : public B
{
    void Foo() const final;
};

// Virtual method definitions

void A::Foo() const
{ std::cout << "A:foo()\n"; }

void B::Foo() const
{ std::cout << "B::foo()\n"; }

void C::Foo() const
{ std::cout << "C::foo()\n"; }

int main()
{
    C c;
    A *a = &c;
    a->Foo();

    return 0;
}