tags:

views:

924

answers:

3

I found a way to extend classes in VBScript, but are there any ways to pass in parameters or overload the constructor? I am currently using an Init function to initialize the properties, but would like to be able to do this when I create the object.
This is my sample class:


Class Test
    Private strText

    Public Property Get Text
     Text = strText
    End Property

    Public Property Let Text(strIn)
     strText = strIn
    End Property

    Private Sub Class_Initialize()  
     Init
    End Sub  

    Private Sub Class_Terminate()   

    End Sub 

    Private Function Init
     strText = "Start Text"
    End Function 
End Class

And I create it


Set objTest = New Test

But would like to do something like this


Set objTest = New Test(strInitText)

Is this possible, or does the object have to be created and initialized in two setps?

+2  A: 

You have to do it in two steps. VB Script doesn't support overloading so you can't modify the default constructor with new parameters. Same goes for Vb6

JoshBerke
+3  A: 

You can work around it by having your Init function returning the object itself...

Class Test
  Private m_s
  Public Function Init(s)
    m_s = s
    Set Init = Me
  End Function
  Public Function Hello()
    Hello = m_s
  End Function
End Class

Dim o
Set o = (New Test).Init("hello world")
Echo o.Hello
svinto
+1  A: 

Just to alter slightly on svinto's method...

Class Test
  Private m_s
  Public Default Function Init(s)
    m_s = s
    Set Init = Me
  End Function
  Public Function Hello()
    Hello = m_s
  End Function
End Class

Dim o : Set o = (New Test)("hello world")

Is how I do it. Sadly no overloading though.

[edit] Though if you really wanted to you could do something like this...

Class Test
    Private m_s
    Private m_i

    Public Default Function Init(parameters)
         Select Case UBound(parameters)
             Case 0
                Set Init = InitOneParam(parameters(0))
             Case 1
                Set Init = InitTwoParam(parameters(0), parameters(1))
             Else Case
                Set Init = Me
         End Case
    End Public

    Private Function InitOneParam(parameter1)
        If TypeName(parameter1) = "String" Then
            m_s = parameter1
        Else
            m_i = parameter1
        End If
        InitOneParam = Me
    End Function

    Private Function InitTwoParam(parameter1, parameter2)
        m_s = parameter1
        m_i = parameter2
        InitTwoParam = Me
    End Function
End Class

Which gives the constructors...

Test()
Test(string)
Test(integer)
Test(string, integer)

which you can call as:

Dim o : Set o = (New Test)(Array())
Dim o : Set o = (New Test)(Array("Hello World"))
Dim o : Set o = (New Test)(Array(1024))
Dim o : Set o = (New Test)(Array("Hello World", 1024))

Bit of a ball ache though.

jammus