Why can't we use a constructor with parameter in derived classes

前端 未结 3 1840
感情败类
感情败类 2021-01-15 20:31

Why is this not possible? I get the following compiler-error when instantiating \"DerivedClass\" with a constructor-parameter:

\'GenericParameterizedConstructor.Deri

相关标签:
3条回答
  • 2021-01-15 20:35

    The deriving class needs to expose the constructor

    public class DerivedClass : BaseClass<String>
    {
        public DerivedClass(string str) :base(str) {}
    }
    
    0 讨论(0)
  • 2021-01-15 20:42

    Constructors aren't inherited - it's as simple as that. DerivedClass contains a single constructor - the public parameterless constructor provided by default by the compiler, because you haven't specified any constructors.

    Note that this has nothing to do with generics. You'd see the same thing if BaseClass weren't generic.

    It's easy to provide constructors for DerivedClass though:

    public class DerivedClass : BaseClass<String>
    {
        public DerivedClass() : base()
        {
        }
    
        public DerivedClass(string value) : base(value)
        {
        }
    }
    
    0 讨论(0)
  • 2021-01-15 20:50

    It would sometimes be helpful if there a way of instructing the compiler to automatically generate for a particular derived class constructors which precisely mimic and wrap all those of the base class. Having such behavior occur by default, however, would be problematic. Many derived classes expect that some of their code will be called whenever an instance of their type is created. Suppose a parent type had two constructors:

    parentType(int foo) {...}
    parentType(string foo) {...}
    

    and a derived type had one:

    derivedType(string foo) {...}
    

    What should be the effect of new derivedType(7);? The compiler would know how to create a new baseType(7);, but if it created a new "blank" derivedType object and then simply called the parent-type constructor, the result would be a derivedType object which had never run any of derivedType's construction code. While some classes wouldn't have any problem with that (and for such classes, the earlier-mentioned hypothetical feature would be helpful), a lot of classes would.

    Incidentally, a somewhat-related issue occurs with protected constructors. In some .net languages including at least the current version of C#, if non-abstract type Foo defines a protected constructor, that constructor may only be used to create instances of derived types. In other languages, including the current vb.net, it's possible for code within a derived type to call a protected constructor of the base type to create a new base-type instance.

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