Why is the constructor not inherited?

As a follow-up question, Base Class Methods Only

Parent methods are inherited by their descendants.

How come constructors (e.g. New ()) are not? Which seems to me to interrupt the inheritance.

Is there an attribute somewhere that designates it as special? (If so, what is it?)

Could you explain what is happening.

+5
source share
5 answers

I suspect the real reason is twofold:

First of all, no static ( Shared) members are inherited in VB # (or C #). While this is consistent with what most OO languages ​​do, it is not a necessary design. Perhaps this was implemented in different ways.

-, , . , , , . , , :

Class Base
    Public Sub New()
    End Sub
End Class

Class Derived : Inherits Base
    Public Property X() As Integer

    Public Sub New(ByVal value As Integer)
        X = value
    End Sub
End Class

' …

Dim foo As New Derived()
Console.WriteLine(foo.X) ' = ???

, .

+4

(, , ) , S T, S , T.

- . :

myS.SomeMethodOfT()    ' works
myS.New()              ' doesn't work -- constructors are special.

, (Shared Visual Basic) , ( ):

Dim myS = New S()      ' can be seen as syntactic sugar for 
                       ' something like myS = S.CreateNew()
+2

, . , .

+1

.

B A, B : A ( ) B ( ).

, ( ).

: B, B, A. , B, A ( , base() # MyBase.New() VB).

B A, . , A , ( ), A.

, !

0

, , . pascal c, - , .

, ...

Class Base
    Public Sub New()
    End Sub
End Class

Class Derived : Inherits Base
    Public Property X() As Integer
    Public Sub New(ByVal value As Integer)
        X = value
    End Sub
End Class

'...   Dim foo As New Derived()

Console.WriteLine(foo.X) '=???

: foo.x . - ... .

Consider another example ...

Class Base
    Public Property X As Integer
    Public Sub New(ByVal value As Integer)
        X = value
    End Sub
End Class

Class Derived : Inherits Base
End Class

'It works ... Dim o as Base = New Base (5) "It is not. It will work in pascal or c ... but not in vb (or presumably C #)

Dim o as Derived = New Derived (5)

The fact is that an inherited class should not override the constructor if it does not change the signature. The reality is that this is an example of how Microsoft takes away a valuable tool because too many programmers are unable to use the tool correctly.

0
source

All Articles