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

寵の児 提交于 2019-12-01 13:04:35

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)
    {
    }
}

The deriving class needs to expose the constructor

public class DerivedClass : BaseClass<String>
{
    public DerivedClass(string str) :base(str) {}
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!