Constructor Inheritance

I tried to understand, but still not sure. If there is a constructor in the base class, will derived classes always call it? I know that they can redefine it (not the right term here, I know - I mean add code to my constructors), but I assume that the constructor is defined in the base class, derivatives will always call it. It's true?

+6
inheritance constructor c #
source share
2 answers

Yes, if there is a constructor without parameters, it will always be called. If there is more than one constructor, you can choose which one should be called using base :

 class Parent { public Parent() {} public Parent(int x) {} } class Child : Parent { public Child(int x) : base(x) { } } 

If there is no constructor without parameters, you will be forced to do this:

 class Parent { public Parent(int x) {} } class Child : Parent { // This will not compile without "base(x)" public Child(int x) : base(x) { } } 
+6
source share

If there is only a constructor without parameters in the base class, the constructor of the child class will always be its first. On the other hand, if you have other constructors defined in the base class, then the child class will have an option for which the base constructor will be called.

+2
source share

All Articles