Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inheritance and the New constructor

Status
Not open for further replies.

bustell

Programmer
Mar 22, 2002
159
US
I must be missing something here. I am trying to create a base class (TestBase) which must be inherited that contains multiple New constructors.

Everything seems to be good until I tried to instantiate a derived class (Test). I am only given the option of the New constructor that does not accept parameters. However, I would like to have a constructor that does use parameters and I would like it in the base class.

Test Classes:
Code:
    Public MustInherit Class TestBase

        Protected _DSN As String
        Public Property DSN() As String
            Get
                Return _DSN
            End Get
            Set(ByVal value As String)
                _DSN = value
            End Set
        End Property
        Public Sub New()

        End Sub
        Public Sub New(ByVal dsn As String)
            Me.New()
            _DSN = dsn
        End Sub
    End Class

    Public Class Test
        Inherits TestBase

    End Class

Now when I go to instantiate the Test class this is allowed:
Code:
Private T As New Test()
But this is not allowed:
Code:
Private T As New Test("testDSN")

Am I missing something with inheritance that I should be aware of? I thought that I would be able to do this. I would like the New(dsn as sting) constructor to be a part of all my derived classes.



Pat B
 
NOpe that's not how it works. Only the derived classes can use the constructors of the base class. So each derived class needs to have the same constructors like this

Public Sub New(ByVal dsn As String)
MyBase.New(dsn)
_DSN = dsn
End Sub

Only way around this is to not use mustinherit.


Christiaan Baes
Belgium

"My old site" - Me
 
Interesting... I wonder why that is.



Pat B
 
Well I think one reason would be that you can't instanciate a class that is declared as MustInherit, think about the meaning of this word, Must-Inherit .. [ponder]

As Chrissie1 said, only derived classes can call its constructor... create a constructor that takes a string as argument for each derived class or remove the MustInherit keyword.

Cheers!

---
[tt][COLOR=white Black]MASTA[/color][COLOR=Black lightgrey]KILLA[/color][/tt] [pipe]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top