The real question is what you want to achieve, and either achieve it in C++, or in another language if you think it would suit the needs better.
Why can't virtual constructors exist in C++?
Imagine one second that it would exist and that your Base
could have a virtual constructor.
Let's keep thing simple, and do not even consider derived classes that need additional arguments in the constructor (like Shape()
and Circle(center,radius)
) nor more complex cases with multiple inheritance and virtual inheritance.
Imagine that in your Derived
class you'd have a member function f()
that would invoke createObject()
. Now you define a class DerivedDerived : public Derived
. And imagine that there is a function g()
in that class that invokes f()
. Two possible semantics:
createObject()
creates an object of the class that invokes it. In this case it would create a Derived
when called via g(). This semantic would fail for polymorphic abstract class that would invoke it, e.g. if Derived
was abstract.
createObject()
creates always an object of the most derived class. But this would require at compile time to know all potential derived classes, or have at runtime additional code everytime you'd create an object. And here we'd be back with the multiple inheritance issue. And most of all, this is not in line with the C++ principle that you should not pay for something you don't need.
Now this is not the only issue. The semantics of C++ is that during the constructor the Base
subobject of Derived
the object is a Base
and doesn't know about Derived
until its construction is finished.
In other words, virtual constructors would conflict with fundamental semantics and assumptions of billions of lines of source code around the globe, just for a few exceptional cases where it could be useful.
How to solve it
As you figured out, the factory pattern could solve a number of use cases. Unfortunately, not exactly yours.
But there's an allost perfect match for your need: a variant of the prototype pattern, which promotes polymorphism, by making sure that classes that need it implement a virtual clone()
function that creates a copy of itself. All you need is to have a virtual createObject()
that only create an object of the same kind instead of cloning it.
Of course this requires some boilerplate code in each class of your inheritance network, but you could extremely well adapt semantics to your needs. Possibly some templating techniques could alleviate this task, but this would be a candidate for a SO question ;-)