Constructor Parameters and Inheritance

后端 未结 4 1011
生来不讨喜
生来不讨喜 2020-12-09 08:35

New to OOP and I\'m confused by how derived-class constructors work when inheriting from a base class in C#.

First the base class:

class BaseClass
{
         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 09:20

    public SubClass(string BaseString, string SubString) : base(BaseString)
    

    This constructor in the derived class says that when you receive two arguments BaseString and SubString, call the base class's constructor with BaseString.

    Thus, doing

    public SubClass(string a, string b) : base(BaseString)
    

    doesn't work, because you are telling it to call the base class's constructor with BaseString but there is no argument called BaseString.

    If you want to instantiate the derived class without passing a String to the base class constructor, the base class needs a default constructor:

    public BaseClass() { }
    

提交回复
热议问题