Search code examples
c++finalkeywordprotectedsubclassing

Is there a way to forbid subclassing of my class?


Say I've got a class called "Base", and a class called "Derived" which is a subclass of Base and accesses protected methods and members of Base.

What I want to do now is make it so that no other classes can subclass Derived. In Java I can accomplish that by declaring the Derived class "final". Is there some C++ trick that can give me the same effect?

(Ideally I'd like to make it so that no class other than Derived can subclass Base as well. I can't just put all the code into the same class or use the friend keyword, since Base and Derived are both templated, with Base having fewer template arguments than Derived does....)


Solution

  • As of C++11, you can add the final keyword (technically a special identifier since it is not actually a keyword) to your class, eg

    class Derived final
    {
    ...
    

    You can read more about the final keyword at http://en.wikipedia.org/wiki/C++11#Explicit_overrides_and_final