Instantiating Class Objects

In Chapter 4, we saw how to declare and instantiate object variables, like the Recordset object, using the Set keyword. Class objects are brought into existence in exactly the same way. The following code

Figure 12-5

segment demonstrates how to declare and instantiate an object variable:

Dim myKennel As clsKennel Set myKennel = New clsKennel

As mentioned earlier, once you instantiate a class, it is referred to as an object instance of that class.

If you were declaring a variable to hold an integer value, you would declare it as an Integer data type, using the Dim intMyVariable As Integer construct. But since we are declaring a variable to contain an instance of a class object, you declare it as an object, but more specifically as an object of the clsSomeClass type, where clsSomeClass is the name you gave to your class. Remember that when you save a named class module, Access understands that it is an object; that's why it appears in the Object Browser. So when you declare a variable of that type, Access allocates sufficient memory to hold a pointer to an instance of your object. That's right, when you instantiate the class object, the variable doesn't contain the object itself, just a pointer to it.

Of course, you could save a line of code by instantiating the object on one line using the New keyword, but it's not the recommended way of doing things. For example:

Dim myKennel As New clsKennel

The simple reason for this is that, although you might save a line of code, programmers often need to know exactly when an object is instantiated, particularly when debugging someone else's code. By using one line to declare the variable and one to instantiate the object, it is quite clear when things happen. The performance impact is negligible.

0 0

Post a comment