[ACCEPTED]-Can you inherit a sub new (Constructor) with parameters in VB?-new-operator
The behavior that you are seeing is "By 22 Design". Child classes do not inherti 21 constructors from their base types. A child 20 class is responsible for defining it's own 19 constructors. Additionally it must ensure 18 that each constructor it defines either 17 implicitly or explicitly calls into a base 16 class constructor or chains to another constructor 15 in the same type.
You will need to define 14 the same constructor on all of the child 13 classes and explicitly chain back into the 12 base constructor via MyBase.New. Example 11
Class ChildClass
Inherits BaseClass
Public Sub New(text As String)
MyBase.New(text)
End Sub
End Class
The documentation you are looking for is 10 section 9.3.1 of the VB Language specification.
I 9 think the most relevant section is the following 8 (roughly start of the second page)
If a type 7 contains no instance constructor declarations, a 6 default constructor is automatically provided. The 5 default constructor simply invokes the parameterless 4 constructor of the direct base type.
This 3 does not explicitly state that a child class 2 will not inherit constructors but it's a 1 side effect of the statement.
Parameterized Constructors cannot be inherited 7 in the same way as instance methods. You 6 need to implement the constructor in the 5 child class and then call the parent's constructor 4 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 3 what I can gather, it's definately not possible 2 in C#, Java or C++ either.
Here is one related 1 post with the same question about C++:
c-superclass-constructor-calling-rules
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.