Object Variables and the New Clause

While the members of an object can be treated like any other variable of the same data type, object variables are quite different from other variables.  That’s because an object variable does not contain the value of the object, it contains a reference (or “pointer”) to the memory where the value is stored.  For example, if we declare a Location variable:

Dim My_loc As Location

This statement creates a pointer, My_loc, to an object of the Location Class.  However, at this time, the My_loc object variable has not allocated any storage for the value of the object and so its pointer is set to “Nothing”.  If you attempt to access a member of My_loc at this time, an error would be generated.  In general, before an object can be used, you must either allocate memory to the pointer (see below), copy a pointer to an existing value or call a method that returns a value pointer.

The standard way of creating (“allocating”) an object value is by using a New clause.  This clause may appear in a Dim statement or in an assignment statement and has the following syntax:

New class_name

where class_name is the name of the class for which you want to create an object value.

For example, the following three cases all declare a location object variable and allocate a Location Object value for it.

Dim My_loc As New Location  ' Create new location value
-or-
Dim My_loc As Location = New Location ' Same as above
-or-
Dim My_loc As Location ' Declares variable only
My_loc = New Location ' Creates the location value

In general, if you are unsure of whether to allocate a data block or not, you should probably go ahead and allocate using the New clause.  Using New unnecessarily will be somewhat less efficient, but GPL automatically takes care of managing allocated object values and so memory is never lost (i.e. you cannot create a memory “leak”).