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

前端 未结 4 1854
迷失自我
迷失自我 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:33

    This is becase when the child class is instantiated, it will also instantiate the base class. By default, it will try to find a arg less constructor. This is work with this code:

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

提交回复
热议问题