Prevent Class Inheritance in C++

How to prevent a derived class being an abstract class in c++?

At first, you are right, not implementing foo in A makes A abstract, not implementing foo in B makes that one abstract as well.

The whole sense of polymorphism is that you provide a common interface for a set of classes. Any derived type can behave as a base type in general, the specific behaviour would deviate only in the details (e. g. like steering in a car, bike or ship, the mechanism is different, but you can steer all of them).

If it doesn't make sense to call foo on B, then first ask 'Why?'! Somehow, B cannot be a true A then, just like a screw driver cannot be a hammer (but both can be tools).

If you find yourself in such trouble, then most likely your design is flawed.

Prevent inheritance of base class

If you make B and C part of A you can mark the constructor of A private so no other classes can inherit directly from A:

public class A
{
private A()
{

}

public class B: A
{
public B()
{

}
}

public class C: A
{
public C()
{

}
}
}

The downside however is that you now have to refer to B as A.B (see edit, this is not needed), but functionality wise the rest of the application is able to instantiate and use classes of type A.B and A.C and inherit from them while prohibiting the ability to instantiate or use A directly (even in the same file/assembly).

So this is invalid anywhere outside of A:

public class D: A
{

}

But this you can use anywhere:

public class E : A.B
{

}

Edit: As noted by Jonathan Barclay you prevent having to use A.B by the following using directive, which will allow you to inherit as normal:

using static MyNamespace.A;

public class D : B
{

}

how to prevent class 'a' from being inherited by another class?


java: final  
vb: NotInheritable (NonOverrideable for properties)
c#: sealed


Related Topics



Leave a reply



Submit