Is it possible to override the constructor of the base class in the derived class?
If so, the how can it be accomplished and in what use case would this be practical? If not, why not?
Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.
Constructor Overriding is never possible in Java. This is because, Constructor looks like a method but name should be as class name and no return value. Overriding means what we have declared in Super class, that exactly we have to declare in Sub class it is called Overriding.
No we cannot override the constructor. A constructor is a special member function of class with the same name as that of class. Its primary purpose is to initialize the data members of the instance of the class. Hence saying that it initializes the data members of the class would be wrong.
Only if the method is pure virtual at this level, it is undefined behavior calling it from the constructor/destructor. In Java, in the other hand, you must not call any overriden method in the constructor as that will be dispatched to the most derived class that has not yet been initialized.
No, you can't override constructors. The concept makes no sense in C#, because constructors simply aren't invoked polymorphically. You always state which class you're trying to construct, and the arguments to the constructor.
Constructors aren't inherited at all - but all constructors from a derived class must chain either to another constructor in the same class, or to one of the constructors in the base class. If you don't do this explicitly, the compiler implicitly chains to the parameterless constructor of the base class (and an error occurs if that constructor doesn't exist or is inaccessible).
No, Constructors are not inherited. You can not override them in derived class.
Reason
A base constructor will always be called, for every class that descends from object, because every class must have at least one constructor that calls a base() constructor (explicitly or implicitly) and every call to a this() constructor must ultimately call a base() constructor.
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