Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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....)

like image 302
Jeremy Friesner Avatar asked Aug 07 '09 21:08

Jeremy Friesner


People also ask

Is subclassing the same as inheritance?

A subclass is the same as an inherited class. In example A, bar is an inner class. An inner class is like a nested type. bar can see all the private stuff from foo but it's not itself a foo (you can't cast bar to foo ).


1 Answers

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

like image 180
Peter N Lewis Avatar answered Oct 02 '22 19:10

Peter N Lewis