Boost logo

Boost :

From: kalin (kalin.eh_at_[hidden])
Date: 2005-01-13 17:44:49


> On Thu, Jan 13, 2005 at 12:49:33PM +1000, kalin wrote:
>
> > Hi All, I've made a simple implementation of making a class
non-derivable.
>
> I can't compile this with GCC3 or Comeau.
> GCC2 lets me compile it (due to its flakey friend implementation) but it
> also allows Bar to inherit from Foo!
>

Should have mentioned I only tested it on VS71.
Did you attempt to instantiate the Bar, or just inherit?

The earlier solution would not even warn about inheritance, but
disallowed instantiation.. not an optimal solution, hopefully something
better can be figured out. :)

> This is a simpler way of preventing inheritance:
>
> class Finaliser
> {
> protected:
> Finaliser(){}
> };
>
> class Final : private virtual Finaliser
> {
> // rest of class as normal
> };
>
> I think I first saw this in Dr. Dobbs in one of their single page tips.

I saw a similar thing in Design and Evolution of C++, but I didn't like
having to worry about derivation type.

The goal was to remove any need to specify correct access or virtual-ness
of the base class, and make it less prone to mistakes.

>
> It doesn't prevent derivation if the derived class has no user-defined
> constructors (since the compiler-generated ones will access the virtual
> base):
> class NotSoFinalNow : public Final { };
>
> But does work if there are user-defined ctors:
> class WillNotCompile : public Final { WillNotCompile() {} }; // error
>

I'll do some more tests with regard to existing/nonexisting ctors/dtors and
see if something a bit more robust can be created. :)

Thanks for the feedback.

kalin


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk