Search code examples
c++final

Why does C++ forbid private inheritance of a final class?


C++11 introduced the final keyword to C++.

It can be used on a virtual method or on a class.

Declaring a class final forbids any kind of inheritance: public, protected and private.

struct A final {
};

class B: private A {
};

 error: base 'A' ^ is marked 'final'

While it can be reasonable to forbid public inheritance (e.g. if my class doesn't have a virtual destructor, or for other reasons), why should I forbid private inheritance?

Might it be that if final forbade only public inheritance, that std::string and its other friends in std would have been final -- as they should -- for not having a virtual destructor?

EDIT:

Howard Hinnant already answered Why the standard containers are not final but still, there is a reason for declaring a class final but allowing private inheritance.


Solution

  • Inheritance is inheritance. Accessibility is orthogonal to it. It only protects from statically treating the derived class as the base, outside the scope of the derived class. It makes no difference at runtime, and if private inheritance was allowed, you could write this:

    struct C {
        virtual void foo() {}
    };
    
    struct A final : C {
        virtual void foo() {}
    };
    
    void baz(A& ref) { ref.foo(); }
    
    class B: private A {
       virtual void foo() {}
       void bar() {
           baz(*this);
       }
    };
    

    Private inheritance doesn't stop you from using run-time polymorphism. If final is meant to fully prevent further overriding, then private inheritance must be included in the prohibition.