Consider the following problem:
You have a class ‘A’ that serves as a base class for a lot of other similar classes, eg. a class called B.
The class A is useful in it self (and already used all over the place) and is hence not abstract.
The crux is that you now wish to enforce a new protocol requiring all classes inheriting from A (including A itself) to implement a method ‘func()’. If a sub class forgets to implement func() there should be a compiler error.
class A {
A func() { ret new A(...) }
}
class B : A {
A func() { ret new B(...) }
}
class C : A {
// Should give error : no func()
}
Is the problem clear? I can’t make A::func() abstract since I want to be able to keep using A as a concrete class. I can’t make it virtual since that would cause sub classes to fall back on the super class (and not give compiler errors).
The only thing that comes close to a solution is creating a new abstract class A* and have all custom types inherit from that and replace all current usages of A as a concrete class with a new class ‘DefaultA’ that inherits from A*. This seems messy. Please tell me there is some other way to do this?
If that is what you need to do, then yes.
In my opinion though, you may wish to reconsider this requirement. I have often implemented similar frameworks, where forcing implementations in sub-classes was a clever trick. What I then found was that as a consumer of these frameworks I would duplicate code or default to some inane implementation (like the empty method). Neither of which is ideal, as they add clutter and noise, and reduce maintainability.
Additionally, if the application of this pattern is as a self-factory (ie your example has sub-classes returning instances of themselves), then you may wish to try something different, like a proper factory pattern. Er, and by “try” I mean leverage an Inversion of Control Container, like Castle Windsor, Ninject, Unity.