Stacking Objects


A stack is a data structure in which you can add items only to the top and remove them only from the top. The technical term is LIFO (last in, first out), but anyone who has ever stacked plates or books knows the concept. You might find it convenient for storing forms, controls, or files. The idea is that you can’t get anything out of a stack in the wrong order because the stack allows only one order. The traditional terminology for stack operations is that you “push” things onto a stack and “pop” them off.


There are many different ways to implement a stack. To illustrate this point, I’m going to start with a stack interface rather than a stack class. (See “Polymorphism and Interfaces” in Chapter 3 for an introduction to interfaces.) I’ll implement three different versions of the stack and test them to see which is the fastest. Here’s the IStack interface:

‘ IStack interface class
Public Sub Push(vArg As Variant)
End Sub

Public Function Pop() As Variant
End Function

Property Get Count() As Long
End Property

The CStackLst class is based on the linked list technique and the CStackVec class is based on the vector technique described earlier in this chapter. The CStackCol class is based on Visual Basic’s Collection class. Because all three stacks implement the same interface, the client program can use any of them with exactly the same code.


As a practical matter, the interface approach doesn’t make much sense. There’s no reason to keep three different implementations of the stack around—you want only the fastest one. So once we figure out which one that is, we’ll use Save As to create the one and only CStack class for the VBCore component.