In .NET can a class have virtual constructor?

Viewed 18976

Can a class have virtual constructor??

If yes, why it is required?

8 Answers

For a flexibility of construction an abstract factory can be used. Lets say we have:

class A {}
class B : A {}

with abstract construction:

class AbstractFactoryA
{
   abstract A Create();
}
 class AbstractFactoryB
{
   override A Create() //or B if language support covariant returns
   {
      ...
      var result = new B(args)
      ... 
      return result;
   }
}

and template construction:

class TemplateFactoryA
{
   TemplateCreate()
   {
      ...
      InternalCreate(args)
      ...
   }
   abstract InternalCreate();
}

Constructors execution works in the form of:

ctor()
{
   base.ctor()
   ...
}

but with exact class.

Is there an language that support abstract factory pattern hidden in syntax sugar. It can be very useful. At the end ctor is a method :)

Related