Suppose there is a base class A
and a class B
derived from A
.
Then, we know that the constructor of class A
is never inherited by class B
. However, when a new object of B
is created, then - the default constructor of the class A
is called prior to the default/custom constructor of class B
is invoked. Maybe the purpose of this is that the fields of class A
need to be initialized to default values.
Now, suppose that class A
has defined a custom constructor. This means that the default constructor of class A
is silently removed by the compiler. Now, on creating a new instance of class B
, which constructor of class A
is automatically called before invoking the class B
's constructor? (How does the class A
fields get initialized in such a case?)
Now, on creating a new instance of class
B
, which constructor of classA
is automatically called before invoking the classB
constructor?
The code will fail to compile, basically. Each constructor has to chain to another constructor, either implicitly or explicitly. The constructor it chains to can be in the same class (with this
) or the base class (with base
).
A constructor like this:
public B() {}
is implicitly:
public B() : base() {}
... and if you don't specify a constructor at all, it will be implicitly added in the same way - but it still has to have something to call. So for example, your scenario:
public class A
{
public A(int x) {}
}
public class B : A {}
leads to a compiler error of:
error CS7036: There is no argument given that corresponds to the required formal parameter
'x'
of'A.A(int)'
However, you can specify a different constructor call explicitly, e.g.
public B() : base(10) {} // Chain to base class constructor
or
public B() : this(10) {} // Chain to same class constructor, assuming one exists
See more on this question at Stackoverflow