Arrays of Objects
| Declare and allocate the array of objects |
| Initialize the array of objects |
| Accessing Methods from an Object Array Element |
| Example |
Declaring and Allocating an Array of Objects
Arrays of objects can be declared, as in the following.
Private empGroup1 (10) As New CEmployee ' declares and allocates an array of CEmployee objects
or
Private empGroup2 (10) As CEmployee ' declares an array of references to CEmployee objects
The first statement sets up an array variable of type CEmployee that refers to a block of eleven objects of type CEmployee.
The second statement sets up an array variable of type CEmployee that does not yet refer to specific objects.
Initializing an Array of Objects
When the New keyword is used to declare an array, as in the declaration of empGroup1 above, the array actually refers to objects that have been instantiated and can be accessed immediately.
If the New keyword is not used, as in the declaration of empGroup2 above, then the array contains only object references, and no objects have been instantiated. If an attempt is made to set one of the attributes of one of the elements, such as empGroup2 (0), the message Object variable or With block variable not set results. In order to instantiate the individual objects, the following approach can be used:
For index = LBound (empGroup2) To UBound (empGroup2)
Set empGroup2 (index) = New CEmployee
Next index
This sets up each element of the array to refer to an instance of the CEmployee class. Each of these objects will be set up with whatever initial values are provided by the CEmployee Initalize method. Recall that the object will not actually be allocated until it is accessed.
Note:
Recall that objects can be instantiated in two steps:
' Declare a reference to an employee object
Dim Emp as CEmployee' Create a new object and save its reference
Set Emp = New CEmployee
However, a similar approach does not work correctly for arrays of objects:
Private empGroup2 (10) As CEmployee ' declares an array of references to CEmployee objects
Set empGroup2 (10) = New CEmployee' does not work
The previous example merely sets the element with index 10 to a new object. The other elements contain only object references.
Accessing Methods from an Object Array Element
Methods associated with an object in an array of objects can be invoked using the syntax
arrayName (index).methodName (arguments)
Print empGroup1 (0).getName ( )
Property procedures are invoked in much the same manner:
arrayName (index).propertyMethodName = value
empGroup1 (0).Firstname = "Matilda"
Example excerpt from the test program.
|
Dim empGroup1(10) As New CEmployee ' declares and allocates the array |