lundi 4 mai 2015

How to prohibit public inheritance but allow private (and protected) inheritance

C++11 introduced the keyword final to forbid future overrides or to prohibit inheritance. The most common example where one may use it is for the case of classes that are not intended to be used as base classes (have e.g. non-virtual destructors). However, sometime we may want to have an is-implemented-in-terms-of relation between two classes (i.e. private inheritance), and not a is-a relationship (public inheritance). However, final prohibits both types of inheritance.

My question is the following: is there any way of allowing private inheritance but forbidding public inheritance (probably not directly, but at least can we "simulate" it)? In this case, there won't be any issues even if we use a class with a non-virtual destructor, as we cannot use directly the derived class via a pointer to base, so we should be fine.

I am thinking of a code like this:

class Base /*final*/ {}; // making it final prohibits both private and public inheritance

class PrivateDerived: private Base{}; // this should work

class PublicDerived: public Base{}; // this shouldn't

int main()
{
    PrivateDerived prvd;
    PublicDerived  pubd; // this should not compile

    // Base* pBase = new PrivateDerived; // doesn't work, so we are ok
}

Aucun commentaire:

Enregistrer un commentaire