Virtual Constructor

Used to create an object with the exact type given at runtime. The general type may be assumed.


OK, that's interesting. In ObjectPascal, I found this:

The most notable feature of ObjectPascal as in Delphi is the use of type variable, and through type variables the usage of VirtualConstructor (yes you can declare a constructor virtual in Delphi). As far as I know there's no other OO typed language having such a useful feature.

If I have this right, it seems that the VirtualConstructor is a feature of DelphiLanguage, but has to be implemented using some sort of support class in other languages.

So we might have

 TFoo = class
  constructor Create; virtual;

TBar = class(TFoo); public constructor Create; override; end;

TFooClass = class of TFoo; //declares a class reference type


var fc: TFooClass; afoo: TFoo; begin fc := TFoo; afoo := fc.Create; // returns a TFoo


fc := TBar; afoo := fc.Create; // returns a TBar

{contrived example - we could just call TFoo.Create or TBar.Create in these cases}


There must be similar features in other typed languages surely?

If you think you need a VirtualConstructor, you may be better off with a ClassFactory.

VirtualConstructor is also a nickname for the FactoryMethodPattern in the DesignPatternsBook

ClassFactory is needed when there's no support for strong typed MetaClassVariable with inheritance support and VirtualMetaClassMethod

MetaClassVariable are especially useful in InitializationSequence?, allowing to build sets of ClassRepository?

View edit of September 4, 2003 or FindPage with title or text search