Reputation: 5098
I have a class A
and I need a subclass of A class B: public A
. How can I achieve that I can inherit from this class but nobody else ever can inherit again from this two classes?
If i make class A
final B can't inherit from A.
Upvotes: 1
Views: 268
Reputation: 1
Just an idea (though I don't think that's actually a good design):
class B;
class A {
// everything's private
friend class B; // << except for class B
};
class B final // << final prevents from further inheritance
: A {
public:
// What you want to publish ...
};
Though as mentioned before, I don't see that much point for class A
unless you want to have more class instantiations like class B
.
Upvotes: 2
Reputation: 474406
There is no way in C++ to say that only one class can inherit from another class. Either a class is final
(and thus uninheritable) or it isn't.
The absolute best you could do is have A
declare its constructors private and make B
a friend of A
. But that would make it difficult for other users to create objects of type A
.
Upvotes: 6
Reputation: 28178
As I commented: I'm unclear on what you want. You want B
to be able to inherit from A
, but no new classes to ever be able to inherit from either? Going on that assumption your best bet is to make A
's ctor private and friend B
, while making B
final.
I don't know what you're after, design wise, but this is bad design. It does, however, answer your question.
Upvotes: 2