Hello,
Why there can be no virtual constructors?in class?What's the reason?
Printable View
Hello,
Why there can be no virtual constructors?in class?What's the reason?
Because there's no need. When you create an object, you explicitly specify the type you're creating.
And if you're creasing a Base, then it's not a Derived object, hence no virtual constructors are necessary.
I think that there are use cases for virtual constructors, but that due to syntactic issues C++ does not have them.
One use case is to clone an object of a derived type, where only the base type is known. Dewhurst in C++ Common Knowledge gives the example of a customer wanting to order the same meal as another customer. You know (at compile time) that the fellow wants a meal, but you do not know what meal he wants since neither customer has actually ordered their meals.
The problem then, is that a copy constructor is invoked with syntax like this:
This would result in type slicing. The workaround is to provide a clone() virtual function that returns an object of the specific derived type (i.e., using covariant return types), so we can write:Code:Meal my_meal(other_meal);
C++ FAQ Lite has an article on this solution: What is a "virtual constructor"?Code:Meal* my_meal = other_meal.clone(); // or wrap the returned pointer in a smart pointer
I can see a reason for a virtual copy constructor, but I'm struggling to find a good reason for a virtual constructor, though.