Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are constructors not inherited in C#?

I'm guessing there's something really basic about C# inheritance that I don't understand. Would someone please enlighten me?

like image 496
Esteban Araya Avatar asked Jan 08 '09 23:01

Esteban Araya


People also ask

Why are constructors not inherited?

In simple words, a constructor cannot be inherited, since in subclasses it has a different name (the name of the subclass). Methods, instead, are inherited with "the same name" and can be used.

Can constructor be inherited yes or no?

Constructors are not inherited. The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters to set the private instance variables of the superclass.

Why are constructors inherited?

Now suppose if constructors can be inherited then it will be impossible to achieving encapsulation. Because by using a super class's constructor we can access/initialize private members of a class. A constructor cannot be called as a method.

Why constructor is not overridden?

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.


2 Answers

Sometimes, when subclassing, you want to restrict the conditions required to create an instance of the class.

Let me give you an example. If classes did inherit their superclass constructors, all classes would have the parameterless constructor from Object. Obviously that's not correct.

like image 113
recursive Avatar answered Oct 14 '22 13:10

recursive


If you think about what would happen if constructors were inherited, you should start to see the problem.

As nearly every type in .NET inherits from Object (which has a parameterless constructor), that means almost every type that you create would be forced to have a parameterless constructor. But there are many types where a parameterless constructor doesn't make sense.

There would also be a problem with versioning. If a new version of your base type appears with a new constructor, you would automatically get a new constructor in your derived type. This would be a bad thing, and a specific instance of the fragile base class problem.

There's also a more philosophical argument. Inheritance is about type responsibilities (this is what I do). Constructors are about type collaboration (this is what I need). So inheriting constructors would be mixing type responsibility with type collaboration, whereas those two concepts should really remain separate.

like image 33
HTTP 410 Avatar answered Oct 14 '22 14:10

HTTP 410