Can a class have virtual constructor??
If yes, why it is required?
Just FYI when people are asking for virtual constructors a very good pattern to look into is InversionOfControl
In .NET we have a couple of IoC containers such as ObjectBuilder, Unity, MEF, Spring.NET. In Java (with risk of showing off my Java incompetence) there's Spring, Tapestry and many others.
IMHO IoC is what makes OO deliver on its promises.
If we look at the definitions of the word constructor and virtual we came to a logical conclusion that a constructor can't be virtual.
A virtual method is by definition a method which is dispatched based on runtime type analysis of the receiver, not the compile-time static type analysis of the receiver.
A constructor is a method called when a new instance of a particular type is created.
Since the runtime type of a newly created object is always the same (*) as its compile-time type, there is no need for virtual constructors: the runtime dispatch would always choose the same method as the static dispatch, so why bother making a difference?
(*) This is not entirely true; there are scenarios involving COM interop in which the runtime type of a construction is not the compile-time type. Many things are weird in the world of legacy interop code.
Declaring something virtual means that it can be overridden by a sub-class of the current class. However the constructor is called when a class is instantiated. At that time you can not be creating a subclass of the class in question so there would never be any need to declare a constructor virtual.
Not directly, but the classic Gang of Four pattern Factory Method achieves what would amount to a virtual constructor of sorts, by deferring instantiation to subclasses.
No, how would it work? All constructors in the hierarchy have to be called when you derive child classes from base classes. Making a constructor virtual would imply otherwise.
Something that may be described as having virtual constructor like behaviour, is when you use the factory pattern. Imagine this scenario:
class AnimalFactory
{
virtual Animal CreateAnimal( return new Animal("Cow"); );
}
The default behaviour of this factory is to create cows. But if we create a derived class:
class DogFactory : AnimnalFactory
{
override Animal CreateAnimal( return new Animal("Dog"); );
}
We are now creating dogs. Of course this is not a true virtual constructor (which is impossible), this is virtual construction.