Is there a way to disallow subclassing

I

Ivan Vecerina

Mohammad said:
Is there way to write a C++ class so that it cannot be subclassed?

There is, but it's unfortunately excessively complicated,
making it inconvenient to use.
It can be done by using virtual inheritance:

// class with private constructor and destructor
class Locker {
friend NotToBeSubclassed;
Locker() {};
~Locker() {};
};

class NotToBeSubclassed : virtual Locker
{
//... whatever
};

The trick is: a most-derived class must call the constructor
of all virtual base classes of its parents. But the private
constructor of 'Locker' is only accessible to the
'NotToBeSubclassed' class, which therefore cannot
be derived from.


hth, Ivan
 
I

Ivan Vecerina

Domenico Andreoli said:
i'm not following you, why is required the virtual inheritance?

The most derived subclass is always responsible for initializing
a virtual base class. A non-virtual base class does not affect
subclasses.


Regards, Ivan
 
T

Thomas Wintschel

Bobo said:
(e-mail address removed) (Mohammad) wrote in message

It's easy: declare all your class constructors private!

of course then you can't construct one either. useful for singletons
though. or, you could have a static method that constructed them for you
and returned a pointer
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top