# How to use a constructor

- How to use a constructor
  - The Program
  - The Code:
  - The Source

A constructor is a method (sub or function) that is executed when an object is initialized.
A constructor makes it possible to set the values of some variables at startup. Have a look at DrawingArea - How to draw some figures. It is another example that shows the use of a constructor.

## The Program

The global variable X is set at startup by the constructor. If the button is clicked, it will be written in the Text property of the Label.

## The Code:

     ' Gambas class file

    X AS String

A variable has to be global in order for it to be visible in different methods (_new() and Button1_Click()). See How to use local and global variables.

    STATIC PUBLIC SUB Main()
      DIM hForm AS Fmain
      hForm = NEW Fmain
      hForm.Show
    END

    PUBLIC SUB _new()
      X = "cool"
    END

'The constructor is a method, called: PUBLIC SUB _new()
'Here, the global variable X is set to "cool".

    PUBLIC SUB Button1_Click()
      TextLabel1.Text = "Constructors are " & X & "!"
    END

## The Source

Download