Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>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.</p> <p>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 <code>Type</code> class, is just an instance of a normal class). So if you have a class called <code>TMyClass</code> - Deplhi naming conventions ;) </p> <pre><code>TMyClass : Class ... </code></pre> <p>You can declare the metaclass like this</p> <pre><code>TMyMetaClass : class of TMyClass </code></pre> <p>Now, you can declare a variable that is of <code>TMyMetaClass</code> type,</p> <pre><code>MyMetaClassVariable : TMyMetaClass ... // Assign the meta class to refer to our concrete class MyMetaClassVariable := TMyClass; </code></pre> <p>And you can construct a new instance through this variable</p> <pre><code>MyClassInstance := MyMetaClassVariable.Create(); </code></pre> <p>Now, the <code>MyMetaClassVariable</code> can refer to any class that is either <code>TMyClass</code> or a specialization thereof. If the constructor is declared virtual, then the variable will be constructed with an instance of that specific class.</p> <p>In the same way, you can declare virtual static methods in Delphi, and call them through an instance of the metaclass.</p> <p>So the other question? Why do we need them? Well, in Delphi, they solve some of the same problems as the <code>Type</code> 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 <code>TextBox</code>, <code>ComboBox</code>, etc) are constructed by calling the virtual constructor on the metatype.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload