Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override a constructor in C#?

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?

like image 971
naval Avatar asked Jun 30 '12 06:06

naval


People also ask

Can you override a constructor?

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.

Why constructor overriding is not possible?

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.

Can we override constructor in derived class?

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.

Do I need to override a constructor in C++?

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.


2 Answers

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).

like image 62
Jon Skeet Avatar answered Sep 21 '22 02:09

Jon Skeet


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.

like image 43
Shezi Avatar answered Sep 23 '22 02:09

Shezi