Emulating Data Structures with Class Modules

Before you can do any work with dynamic data structures, you need to understand how to use class modules to emulate the elements of these structures. In Figure 6.1, for example, each element of the structure contains a piece of data and a reference to the next element. How can you create a class module that does that?

It’s easy: create a class module named ListItem with two module-level variables:

Dim Value As Variant
Dim NextItem As ListItem

The first variable, Value, will contain the data for each element. The second, NextItem, will contain a reference to the next item in the data structure. The surprising, and somewhat confusing, issue is that you can create a variable of the same type as the class in the definition of the class itself. It’s just this sort of self-referential declaration that makes dynamic data structures possible in VBA.

To add an item to the list, you might write code like this in your class module:

Public Function AddItem(varValue As Variant) As ListItem
    Set NextItem = New ListItem
    NextItem.Value = varValue
    ' Set the return value for the function.
    Set AddItem = NextItem
End Sub

The first line of the procedure creates a new item in the data structure and makes the NextItem variable in the current element refer to that new element. The second line uses NextItem to refer to the next element and sets its Value variable to the value passed to the current procedure, varValue. The final line sets up the function call to return a reference to the new item, just added to the list.

In reality, you probably wouldn’t write a data structure this way, because it provides no way to find a particular item or the beginning or end of the list. In other words, there’s something missing that makes these structures possible: a reference to the entire structure. The next section tells you how you should actually create such a data structure.

How about the complicated binary tree structure shown in Figure 6.2? The only difference between this structure and a linear list is that each element in this structure maintains a pointer to two other structures rather than just one. The class module for an element (class name TreeItem) of a binary tree structure might contain these elements:

Public Value As Variant
Public LeftChild As TreeItem
Public RightChild As TreeItem

© 1997 by SYBEX Inc. All rights reserved.