Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 Allow inheritance only to certain classes

I have a base class that I'd like to prevent inheritance by most classes, but allow it for a handful of classes that I can hard code in. Is this possible in C++? Is it easier with C++11?

I thought perhaps I'd use the final argument, but that prevents any inheritance at all.

// This can be derived by anyone
class Base{
...
}

// This should only be derived by those I say can derive it
class Base2: public Base{
    protected:
         int SpecialVar;
}

The reason I want this is that some classes need to have access to SpecialVar while it doesn't make sense for the other classes. It still makes sense for all classes to have the functionality of Base.

like image 350
jlconlin Avatar asked Aug 31 '25 16:08

jlconlin


2 Answers

class X 
{   
    private:
        X() {}

        friend class D;
};  

class D: public X
{   
};  

class Y: public X // will fail, because it can't access X::X()
{   
};  
like image 150
Klaus Avatar answered Sep 02 '25 18:09

Klaus


Instead of making your derived classes friends, another way (that may or may not make sense, depending on the concrete classes you're dealing with), is to nest them.

class Base {
    Base() { }
public:
    class Derived;
};

class Base::Derived : Base {
};

class CannotDerive : Base {
};

int main() {
    Base::Derived x; // ok
    CannotDerive y; // error
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!