开发者

What is the use of calling base class's constructor if there is no overloading constructor available

Do we have any advantage or is it just tradition to call base class constructor like #1, do both #1 and #2 differ? (I have used #2 when I happen to have overloading constructor for BaseClass, but why we ).

public class BaseClass
{
    public BaseClass()
    {
        Console.WriteLine("From Base");
    }
}

#1

public class DerivedClass
    : BaseClass
{
    public DerivedClass()
    :base()
    {
        Console.WriteLine("From Derived");
    }
}

#2

public class DerivedClass
  开发者_JS百科  : BaseClass
{
    public DerivedClass()
    {
        Console.WriteLine("From Derived");
    }
}


No, there is no difference. In case #2, the compiler will generate the call to the base class constructor (if there is a parameterless base class constructor available, that is). Adding such a call manually is a style question. It is only compulsory when there is no parameterless base class constructor available, so the compiler can't decide itself how to call it.


They're basically the same. The parameterless constructor of the base class gets called implicitly if you don't specify anything.

That's also why #2 would give you an error if the base class didn't have a parameterless constructor. (#1 would, too, but the fact that #2 gives you an error tells you that it tries to call a parameterless base constructor even if you don't specify the call to it)


As a rule, I generally use #1 if the derived class specifically needs the base class's constructor to run before it. In reality there's no difference to the compiler, but it makes it clearer that there's a dependency. This can be very relevant if you ever consider porting to other platforms. In Delphi for example, a constructor will not call the base class' constructor unless you specifically tell it to; if I were porting the code to Delphi, I'd be more likely to remember to do that with #1.

For example if the base class instantiates a list, and the derived adds to it, I'd use #1. If the derived constructor simply initialises a local field, I'd use #2.


There is no difference. The reason why : base() syntax exists is so that you can call a non-default constructor (with parameters). It would feel arbitrary if the default constructor could not be called the same way.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜