views:

187

answers:

1

I read about virtual constructors are used for implementing some design patterns, but didn't understood any need of virtual constructors. So what are virtual constructors and why we really need them?

+4  A: 

In most programming languages, afaik, you cannot find virtual constructors. Which override of a virtual members are evaluated at runtime after an object is constructed, but in most languages you need to know the actual class when constructing the instance. Therefore virtual constructors make no sense in these languages.

In .NET, you can get a similar solution through reflection, i.e. you can construct an object through an instance of the Type class that represents the object you want to construct. And with generic support, you can also achieve something similar, but it's not virtual constructors.

The only programming language that I have worked with that have true virtual constructors is Delphi. In Delphi, there is a specific "Metaclass type", i.e. a specific programming construct that represents a metaclass (whereas in .NET, the meta class, the Type class, is just an instance of a normal class). So if you have a class called TMyClass - Deplhi naming conventions ;)

TMyClass : Class ...

You can declare the metaclass like this

TMyMetaClass : class of TMyClass

Now, you can declare a variable that is of TMyMetaClass type,

MyMetaClassVariable : TMyMetaClass
... 
// Assign the meta class to refer to our concrete class
MyMetaClassVariable := TMyClass;

And you can construct a new instance through this variable

MyClassInstance := MyMetaClassVariable.Create();

Now, the MyMetaClassVariable can refer to any class that is either TMyClass of a specialization hereof. If the constructor is declared virtual, then the variable will be constructed with an instance of that specific class.

In the same way, you can declare virtual static methods in Delphi, and call them through an instance of the metaclass.

So the other question? Why do we need them? Well, in Delphi, they solve some of the same problems as the Type class in .NET, allowing you to construct objects where you don't know the class name at design time. For example, when you design a form and you put in a bunch of controls, this data has to be serialized by the designer, and deserialized. When the form is deserialized, then it is actually the metatypes that are read, and the correct instances (be it TextBox, ComboBox, etc) are constructed by calling the virtual constructor on the metatype.

Pete
Delphi syntax is correct.
Gamecat
@Gamecat - thanks, I removed my "disclaimer" ;) No need for that as noise then.
Pete