Constructors and Inheritance

后端 未结 10 938
臣服心动
臣服心动 2020-12-16 15:18

Lets take an example in C#

public class Foo
{
    public Foo() { }
    public Foo(int j) { }
}

public class Bar : Foo
{

}

Now, All the pu

相关标签:
10条回答
  • 2020-12-16 15:51

    The Foo constructor can only know how to initialize a Foo object, so it makes no sense that it should also know how to initialize any potential subclass

    public class Bar : Foo
    {
    public Bar(int i) : base(i) { }
    }
    

    The story the constructor tells is: "Hey base class please do whatever work you need to do to be in a good state so that I can go ahead and set up myself properly".

    0 讨论(0)
  • 2020-12-16 15:53

    Suppose constructors were inheritable. How would you disable the inherited constructors in the many cases were they don't make sense for a subclass?

    Rather than complicating the language with a mechanism to block inheritance, the language designers opted for simply making constructors not inheritable.

    0 讨论(0)
  • 2020-12-16 15:58

    Some discussions

    • Joel's forum
    • Eric Gunnerson's blog

    The basic idea is to provide as much control to the creator as possible. And you can have private bases. How'd you create the object then?

    0 讨论(0)
  • 2020-12-16 16:02

    The simple answer is that the language doesn't work that way.

    The real question you are asking for though is why it doesn't work that way :-) Well it is an arbitrary choice, and it follows on from C++ and Java (and very possibly many other langauges that influenced C#).

    The likely reason is that the compiler will only generate a constructor that takes no arguments and simply calls the parent is that if you want more than what the compiler makes you do it yourself. This is the best choice since odds are you do more than suply calling the parent constructor.

    0 讨论(0)
提交回复
热议问题