简体   繁体   中英

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 instance 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.

如果你不调用基类的构造,是怎样一个应该知道的是, int x在B是相同的int x如A?

类A没有无参数的构造函数,因此您必须从B的构造函数调用A(int x)。

B继承自A,因此在创建B的实例时,它也是A,因此需要调用A的构造函数进行初始化。

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.

当您创建B时创建A的实例,因为B继承了实例A

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM