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?
相关问题
- how to define constructor for Python's new Nam
- Keeping track of variable instances
- Object.create() bug?
- std::vector of objects / pointers / smart pointers
- Name for a method that has only side effects
相关文章
- 接口B继承接口A,但是又不添加新的方法。这样有什么意义吗?
- Java call constructor from constructor
- NameError: name 'self' is not defined, eve
- What CursorAdapter have I to use?
- Implementation Strategies for Object Orientation
- Check if the Type of an Object is inherited from a
- is Object.getPrototypeOf() same as Object.construc
- When to use Interfaces in PHP
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 calledTMyClass
- Deplhi naming conventions ;)You can declare the metaclass like this
Now, you can declare a variable that is of
TMyMetaClass
type,And you can construct a new instance through this variable
Now, the
MyMetaClassVariable
can refer to any class that is eitherTMyClass
or a specialization thereof. 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 itTextBox
,ComboBox
, etc) are constructed by calling the virtual constructor on the metatype.