Why is it necessary for a base class to have a constructor that takes 0 args?

前端 未结 4 1836
迷失自我
迷失自我 2021-02-18 14:18

This won\'t compile:

namespace Constructor0Args
{
    class Base
    {
        public Base(int x)
        {
        }
    }

    class Derived : Base
    {
    }         


        
4条回答
  •  梦如初夏
    2021-02-18 14:45

    When you derive a class from another, the base class will be called before the derived classes constructor. When you don't explicitly call a constructor you are essentially writing

    class Derived : Base
    {
        public Derived() : base()
        {
        }
    }
    

    Since the Base class doesn't have a 0 argument constructor, this is invalid.

提交回复
热议问题