How can I call a base class's parameterized constructor from a derived class if the derived class has no parameterized constructor?

前端 未结 3 910
轻奢々
轻奢々 2020-12-21 06:58

I have a base class with two constructors: a default constructor and a parameterized constructor. Another class inherits from that base class and it only has a default const

相关标签:
3条回答
  • 2020-12-21 07:19

    It's not entirely clear what your question is, but I suspect you either want to add an explicit parameterless constructor to your child class:

    // Parameterless child constructor calling parameterized base constructor
    public Child() : base("foo", "bar") {
    }
    

    or add both a parameterized and parameterless one:

    public Child() {
    }
    
    public Child(string foo, string bar) : base(foo, bar) {
    }
    

    Note that constructors aren't inherited - so just because a base class has a particular constructor signature doesn't mean you can instantiate a class using that signature. The child class has to provide it itself.

    Any compiler-provided parameterless constructor will always call the parameterless constructor of its base class.

    0 讨论(0)
  • 2020-12-21 07:20

    Something like this?

    class Parent
    {
        public Parent(){}
        public Parent(string s) {}
    }
    
    class Child : Parent
    {
        public Child() : base("42") { }
    }
    
    0 讨论(0)
  • 2020-12-21 07:27

    Here you go:

    // Parent class
    class Parent
    {
        public Parent()
            {
            // Paremeterless constructor
            }
    
            public Parent(string a, int b)
            {
            // Paremterised constructor
            }       
    }
    
    
    // Child class       
    class Child : Parent
    {
        public Child()
                    :base("hi", 10)
            {
            // Parameterized constructor of the base class is invoked   
            }
    }
    
    0 讨论(0)
提交回复
热议问题