Constructor Arguments in VBScript!

Article Tools

Our Class Inheritance Parser has just received a major update. Among the changes is the support for Constructor Arguments.

Most programming languages allow you to pass parameters when you create an instance of your class. These are called constructor arguments. VBScript’s constructor (the Class_Initialize sub) can not receive parameters, so usually we must resort to solutions as a “Build” or “Start” sub, in addition to the actual constructor, in order to relay the parameters.

Well, No more! The class parser allows support for constructor arguments in the following way:

1. Update your Class_Initialize Sub by adding parameters in a comment right after the sub’s header. For example: Sub Class_Initialize ‘(Param1, Param2, SomeCrazyName).

The parameters can have any legal name you’d wish them to have. Do not use ByVal or ByRef prefixes (the parameters will always be ByVal).

'An example for the new constructor format
Private Sub Class_Initialize '(Param1, Param2)
    'You can keep you Class_Initialize sub as private - it will still work!
    Msgbox Param1 'You can use you parameters just like any other variable
    Param2.Add "Some", "Thing" 'You can even pass objects, such as dictionaries
End Sub

2. Use the same comment method to pass parameters to the constructor when you create a new instance of your class.

For example: Set oMyClass = New clsMyClass ‘(5, “Something”, SomeVariable)

You can either pass the relevant value directly (e.g. 5, “Something”), or use an existing variable (e.g. SomeVariable).

'An example for the new object initialization format
Set oMyClass = New clsMyClass'("Something", oDic)

'You can pass strings, numbers, other vairbales and objects
Previous postSecret Methods of QTP Objects Next postClass Inheritance in VBScript – Now at your Doorstep!

Related Posts

Post Your Comment

You must be logged in to post a comment.