开发者

Why to call base constructor?

Having code like this:

class A
{
  public A(int x)
  {}
}
class B:A
{
  public B(int x):base(3)
  {}
}

I do not get it. The class B is independent child of class A, why I need to call its constructor? I am confused as it looks like the instance of A is created when I create insta开发者_StackOverflow中文版nce of B..


Calling the base class constructor lets you initialize things you're inheriting from the base class.

class A
{
  private int foo;
  public int Foo { get { return foo; } }
  public A(int x)
  {
      foo = x;
      OpenConnectionOrSomething();
  }
}
class B:A
{
  public B(int x) : base(x)
  {
      // can't initialize foo here: it's private
      // only the base class knows how to do that
  }

  // this property uses the Foo property initialized in the base class 
  public int TripleOfFoo { get { return 3*Foo; } }
}


Class B is not independent of class A: it inherits class A and is thus an "extension" of that class.

You don't create a separate instance of A when you create B; the functionality of A is part of what you're creating. Calling A's constructor allows that functionality to initialize if necessary.


If you don't call the base constructor, how is A supposed to know that the int x in B is the same int x as in A?


Class A has no parameterless constructor, hence you have to call A(int x) from the constructor of B.


B inherits from A, so when you create an instance of B it is also an A, so the constructor for A needs to be called to do any initialisation.


Reason is based class defines that it requires a parameter for its constructor. You are inheriting so you will have to respect requirements of A.


When you create an instance of a derived class, you always have to call the base constructor, there is no way around it. However, if the base class has a parameterless constructor, then you don't have to specify the call to the base constructor, if you leave it out it will implicitly call the parameterless constructor. If the base class has no parameterless constructor (like in your example), you have to specify which base constructor to call, and what parameters to send to it.

When you create an instance of the class B, you are kind of creating an instance of the class A, because the B instance is an A instance. The constructor in the base class has to be called to initialise any members that you might inherit. The object is first initialised as an A instance, then as a B instance.


The instance of A is created when you create B as B inherits instance A

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜