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

Tip

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.