Reputation: 15054
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
.
Upvotes: 4
Views: 1316
Reputation: 12259
Other possibility is with a private destructor (specially if A
is an abstract class, since you don't need instances of A
):
class A
{
private:
virtual ~A() = 0;
};
A::~A() {}
class B : public A // Compilation error: ~A() is private.
{};
However, if B
is one of your classes with permission to inherit from A, make it friend of A
:
class A
{
private:
friend class B;
virtual ~A() = 0;
};
A::~A() {}
class B : public A // Fine.
{};
Upvotes: 0
Reputation:
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
}
Upvotes: 5
Reputation: 25613
class X
{
private:
X() {}
friend class D;
};
class D: public X
{
};
class Y: public X // will fail, because it can't access X::X()
{
};
Upvotes: 5