Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

oop - C# inheritance and default constructors

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Now, on creating a new instance of class B, which constructor of class A is automatically called before invoking the class B 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...