An Object Variable Is a Pointer

There are some very important differences between object variables and nonobject variables, such as those of type Integer, Single, or String. As we have mentioned, a nonobject variable can be thought of as a name for a location in the computer's memory that holds some data. For instance, in the code:

Dim iVar As Integer iVar = 123

the variable iVar is a 4-byte memory location that holds the integer value 123. This can be pictured as in Figure 9-2. (Actually, the 4-byte memory location holds the value 123 in binary format, but that is not relevant to our discussion.)

Figure 9-2. Integer variables in memory

Further, if we were to write:

Dim iVar2 As Integer iVar2 = iVar iVar2 = 567

we would not expect the last line of code to have any effect upon the value of the variable iVar, which should still be 123. This is because iVar and iVar2 represent different areas of memory, as pictured in Figure 9-2.

However, an object variable is not the name of a memory location that holds the object. Rather, an object variable is the name of a memory location that holds the address of the memory location that holds the object, as shown in Figure 9-3. Put another way, the object variable holds a reference to or points to the object. For this reason, it is an example of a pointer variable, or simply a pointer. In Figure 9-3, the object variable rng points to an object of type Range, namely, the first column in the active sheet.

Figure 9-3. An object variable in memory frig aJdr«s of -►


The code that goes with Figure 9-3 is:

Dim rng as Range

Set rng = ActiveSheet.Columns(l)

One of the consequences of the fact that object variables are pointers is that more than one object variable can point to (or refer to) the same object, as in:

Dim rng as Range Dim rng2 as Range

Set rng = ActiveSheet.Columns(l) Set rng2 = rng

This code creates the situation pictured in Figure 9-4.

Figure 9-4. Two object variables referencing the same object

We emphasize that while rng and rng2 are different object variables, they hold the same value and so, point to the same object. Thus, we can change the first column using either of these object variables.

It is important when programming with objects to keep very careful track of all object variables and what they are referencing. Furthermore, it is generally not a good idea to have more than one object variable pointing to the same object (as in Figure 9-4) unless there is a compelling reason to do so. It is very easy to change the object using one object variable (say rng) and then later use the other variable (rng2), thinking it refers to the unchanged object.

0 0

Post a comment