Can a class have virtual constructor??
If yes, why it is required?
In C++, the constructor cannot be virtual, because when a constructor of a class is executed there is no virtual table in the memory, means no virtual pointer defined yet. So, the constructor should always be non-virtual. But virtual destructor is possible.
[20.8] What is a "virtual constructor"? An idiom that allows you to do something that C++ doesn't directly support. You can get the effect of a virtual constructor by a virtual clone() member function (for copy constructing), or a virtual create() member function (for the default constructor).
1) Virtual constructor DO NOT exists. Because defining something as virtual means ,you are actually assigning a pointer the virtual look up table for that object and not actually creating that object. So virtual constructor is not at all possible. 2) We do not need virtual constructor functionality.It do not exist.
Yes, an abstract class can have a constructor, even though an abstract class cannot be instantiated.
If you do not provide any constructors for your class or struct, C# is going to create one by default. This, in turn, instantiates the object and sets member variables to the default values based on their datatypes.
no, a class cannot have a virtual constructor.
It doesn't make sense to have a virtual constructor. The order in which objects are constructed in C# is by constructing derived classes first, so the derived constructor is always called since the class you want to call is well known at the time of construction.
The other thing is, if you actually type this code out, you can quickly see that it makes very little sense at all
If you had:
public class BaseClass { public virtual BaseClass() { } }
and then
public class InheritedClass : BaseClass { //overrides baseclass constructor but why would you do this given that the //constructor is always going to be called anyway?? public override InheritedClass() { } }
A virtual method is by definition a method which is dispatched based on runtime type analysis of the receiver, not the compile-time static type analysis of the receiver.
A constructor is a method called when a new instance of a particular type is created.
Since the runtime type of a newly created object is always the same (*) as its compile-time type, there is no need for virtual constructors: the runtime dispatch would always choose the same method as the static dispatch, so why bother making a difference?
(*) This is not entirely true; there are scenarios involving COM interop in which the runtime type of a construction is not the compile-time type. Many things are weird in the world of legacy interop code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With