Creating a class instance


Create class instance

To create a new class instance define a new variable with the classname as the type of the variable and assign an instance of the class to the classvar with the New statement.


Dim classvar As classname

classvar = New classname()


This will allocate the memory for a new object of type classvar and store a pointer to it in the variable classvar. This variable may be used in the following code to reference the object.


Using a constructor method

Whenever you want to create a new class instance with a statement like cvar = New classname() it may be necessary to initialize some values within the class memory. To do this you have to create a method with the name New in the class body. We will call this type of method constructor method. Whenever the parser can find a constructor method in the class definitions it will call the method when creating a new object for this class.

A constructor method may be called with or without parameter values. If calling it with some parameter values the types of the values for the call must match with the parameter types of the method definition of the New method. You may define more than one New method within a class with different parameter types. The HBasic parser will search for the first New method with matching types and show an error message if he cannot find one.

When creating a new class instance at runtime the memory for the object will be created first, passing the pointer to the new unitialized memory block to the New method next. If there is no constructor method the object memory will only be initialized with 0 bytes.

The following example will create two class instances with different types of parameters for the New method. The value of the classlocal variable should therefore be initialized with 1122 for the first object and 3344 for the second object. Printing this result on the screen will prove that the classlocal variable has been initialized correctly.


Class c
Dim i As Integer

Sub New( ival As Integer )
i = ival
End Sub

Sub New( dval As Double )
i = 3344
End Sub

End Class

Dim gc As c

Sub button1_clicked()
gc = New c( 1122 )
Print gc.i

gc = New c( 11.22 )
Print gc.i
End Sub

Example code_examples/class/ex_class_new.bas: Create class instances