Event Procedures in the Class Module

An event is basically an action recognized by an object. Custom classes recognize only two events: Initialize and Terminate. These events are triggered when an instance of the class is created and destroyed, respectively.

The Initialize event is generated when an object is created from a class (see the preceding section on creating an instance of a class). In the CEmployee class example, the Initialize event will also fire the first time that you use the emp variable in code. Because the statements included inside the Initialize event are the first ones to be executed for the object before any properties are set or any methods are executed, the Initialize event is a good place to perform initialization of the objects created from the class.

As you recall, in the CEmployee class, Id is read-only. You can use the Initialize event to assign a unique five-digit number to the m_ld variable.

1. In the CEmployee class module, enter the following Class_Initialize procedure:

Private Sub Class_Initialize() Randomize m_Id = Int((99999 - 10000) * Rnd + 10000) End Sub

The Class_Initialize procedure initializes the CEmployee object by assigning a unique five-digit number to the variable m_ld. To generate a random integer between two given integers where ending_number = 99999 and beginning_number = 10000, the following formula is used:

=Int((ending_number-beginning_number)*Rnd +beginning_number)

The Class_Initialize procedure also uses the Randomize statement to reinitialize the random number generator. For more information on using Rnd and Integer functions, as well as the Randomize statement, search the online help.

The Terminate event occurs when all references to an object have been released. This is a good place to perform any necessary cleanup tasks. The Class_Terminate procedure uses the following syntax:

Private Sub Class_Terminate()

[cleanup code goes here] End Sub

To release an object variable from an object, use the following syntax: Set objectVariable = Nothing

When you set the object variable to Nothing, the Terminate event is generated. Any code in this event is executed then.

0 0

Post a comment