Can you inherit a sub new (Constructor) with parameters in VB?

风流意气都作罢 提交于 2019-12-04 22:12:53

The behavior that you are seeing is "By Design". Child classes do not inherti constructors from their base types. A child class is responsible for defining it's own constructors. Additionally it must ensure that each constructor it defines either implicitly or explicitly calls into a base class constructor or chains to another constructor in the same type.

You will need to define the same constructor on all of the child classes and explicitly chain back into the base constructor via MyBase.New. Example

Class ChildClass
  Inherits BaseClass
  Public Sub New(text As String)
    MyBase.New(text)
  End Sub
End Class

The documentation you are looking for is section 9.3.1 of the VB Language specification.

I think the most relevant section is the following (roughly start of the second page)

If a type contains no instance constructor declarations, a default constructor is automatically provided. The default constructor simply invokes the parameterless constructor of the direct base type.

This does not explicitly state that a child class will not inherit constructors but it's a side effect of the statement.

Jose Basilio

Parameterized Constructors cannot be inherited in the same way as instance methods. You need to implement the constructor in the child class and then call the parent's constructor using MyBase.

Public Class ChildClass
    Inherits BaseClass

    Public Sub New (ByVal SetText As String)
      MyBase.New(SetText)
    End Class
End Class

Public Class TestClass
  Public TestChild AS New ChildClass("c")
End Class

This limitation is not VB specific. From what I can gather, it's definately not possible in C#, Java or C++ either.

Here is one related post with the same question about C++:
c-superclass-constructor-calling-rules

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