Final virtual functions

suggest change

C++11 introduced the final specifier. On a virtual function, it forbids further overriding:

class Base {
public:
    virtual void foo() {
        std::cout << "Base::Foo\n";
    }
};

class Derived1 : public Base {
public:
    // Overriding Base::foo
    void foo() final {
        std::cout << "Derived1::Foo\n";
    }
};

class Derived2 : public Derived1 {
public:
    // Compilation error: cannot override final method
    virtual void foo() {
        std::cout << "Derived2::Foo\n";
    }
};

On a member function, final is allowed only when that function is virtual. It cannot be applied to a non-virtual member function. It can also be applied to a class, as described in Final classes and structs.

override is a separate specifier. It makes the program ill-formed if the function does not override a virtual function of a base. It does not stop a further derived class from overriding that function. final does.

override and final may be combined:

class Derived1 : public Base {
public:
    void foo() final override {
        std::cout << "Derived1::Foo\n";
    }
};

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents