Hello,
Why there can be no virtual constructors?in class?What's the reason?
This is a discussion on Why there can be no virtual constructors?? within the C++ Programming forums, part of the General Programming Boards category; Hello, Why there can be no virtual constructors?in class?What's the reason?...
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.
For information on how to enable C++11 on your compiler, look here.
よく聞くがいい!私は天才だからね! ^_^
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
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
I can see a reason for a virtual copy constructor, but I'm struggling to find a good reason for a virtual constructor, though.
For information on how to enable C++11 on your compiler, look here.
よく聞くがいい!私は天才だからね! ^_^