Derived class explicit base constructor call

2019-06-05 08:10发布

问题:

I am trying to learn C#. The below data is from a Microsoft C# help website. I don't understand this statement, "If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor by using base."

I thought that if there is no default constructor for a class, C# will automatically assign default values to int, char or whatever is declared in a class. If a base class does not have a constructor and it has a child class, does the rule mentioned in the last sentence not apply? Please clarify.

In a derived class, if a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly. This means that the following constructor declarations are effectively the same: C#

     public Manager(int initialdata)
     {
         //Add further instructions here.
      }

C#

     public Manager(int initialdata)
    : base()
    {
          //Add further instructions here.
     }

If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor by using base.

回答1:

If you do not define a constructor for a class:

public class DemoClass
{
   public void SomeFunction() { }
}

C# will add a default (parameterless) constructor for you. In this case; nothing special needs to be done with derived classes, as they will use the provided default constructor. Of course, you can always define your own default (parameterless) constructor:

public class DemoClass
{
   public void DemoClass() { }

   public void SomeFunction() { }
}

Which still doesn't require anything special for derived classes, since they can still use it. If however, you define a parameterized constructor, without defining a default:

public class DemoClass
{
   public void DemoClass(string argument) { }

   public void SomeFunction() { }
}

Now there is no default (parameterless) constructor for derived classes to use; and you need to say which constructor to use with base:

public class DerivedClass : DemoClass
{
   public DerivedClass() : base(String.Empty) { }
}