Using a Class Through an Interface

Now, let’s look at how the client may use the class through the interface. The first step is for the client to declare a variable of the type of the interface as follows:

Dim Acct As IAccount

What exactly happens when you declare a variable such as in the preceding line of code? Visual Basic allocates some memory (4 bytes) to hold a memory address for the object. VB does not actually create the object in memory until it is told to do so. However, it does allocate a container known as Acct to hold the memory address of the object once it is created. The Acct container will hold the memory address &H00000000 (that is, a null pointer) when the variable is declared. Figure 2-3 shows a representation of the Acct memory variable.

Memory representation of the Acct variable

Figure 2-3. Memory representation of the Acct variable


If you are an experienced C++ developer, you may find it interesting to examine the layout of VB objects in memory. VB provides several undocumented functions to enable you to obtain the memory address of an object. These functions are: VarPtr, ObjPtr, and StrPtr. VarPtr returns the address of a variable. ObjPtr returns the address of an object. Therefore, if Acct were the variable, you could ask VB to report the address of the variable itself with the VarPtr function, or you could ask VB to report the address of the object that Acct is pointing to with ObjPtr. The function ...

Get COM+ Programming with Visual Basic now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.