lang • new


Object = NEW Class [ ( Constructor parameters... ) ] [ AS Name ]

Instantiates the class Class.

If a name is specified, the new object will be able to raise events by calling a public procedure or function in its "parent".

If you forget to specify the Name part, your object will never raise events!

NEW is not an operator. You can only use it within an assignment.

But you can use the Object.New function instead.

Instantiating Forms (gb.qt4)

The Form class is by default its own event observer, using the event name Form. This is what allows you to write

Public Sub Form_Open()
  Print "I'm here"

inside of a form's class file to intercept events of the same form.

If you create an instance of a form using the New MyForm As Name syntax, this will no longer happen. The form will be attached to the current object, and especially (since each object can have at most one default event observer) it will not be attached to itself.

So the Form_Open() event handler inside your form's code will not be called anymore. If you want multiple classes to receive events of a single object, use the Observer class.

Common event handlers

Two different objects can have the same event name. Thus, you can manage events of multiple objects in the same event procedure, provided these objects raise the same events.

This feature is used by the IDE for implementing the Group property.


hButton = New Button(Me) As "MyButton"
Public Procedure MyButton_Click()

  Print "My button was clicked !"

' This example creates 9*9*9 small textboxes which can be accessed through the
' public Object[] array objIsImpossible

Public bIsInitialised As Boolean
Public objIsImpossible As Object[]

Public Sub Form_Open()

Dim iR As Integer
Dim iR2 As Integer
Dim iC As Integer
Dim iC2 As Integer
Dim iDigit As Integer
Dim iX As Integer
Dim objTextBox As TextBox

If Not bIsInitialised Then
  objIsImpossible = New Object[] ' Need to create the array
  iX = 0
  For iR = 0 To 8
    For iC = 0 To 8
      For iDigit = 0 To 8
        iR2 = iDigit Mod 3
        iC2 = iDigit / 3
        objTextBox = New TextBox(Me) ' create the next of the 9*9*9 TextBoxes
        objTextBox.X = (iR * 3 + iR2) * 12 + 2
        objTextBox.y = (iC * 3 + iC2) * 12 + 2
        objTextBox.Width = 10
        objTextBox.Height = 10

        objIsImpossible.Add(objTextBox, iX)

        iX = iX + 1
      Next '  iDigit
    Next '    iC
  Next '      iR


Dynamic instanciation

Object = NEW ( ClassName [ , Constructor parameters... ] ) [ AS Name ]

That second syntax allows you to specify the class name dynamically as a string.


' This creates an 3x3 array of float.
Dim MyArray As New Float[3, 3]
' And this too
Dim MyArray As Object
Dim MyClassName As String
MyClassName = "Float[]"
MyArray = New (MyClassName, 3, 3)

See also