Creating objects


So far, our fantasy implementation of B-- has been able to keep kind of close to earth. C++ COM programmers might actually recognize part of our implementation of IUnknown. But creating new instances of objects presents some problems that we can’t easily get around when we’re inventing a language that handles COM but doesn’t support pointers.


I’m going to cop out by saying that the CreateInstance function resides in the B-- run-time library (so that I don’t have to show code for it). It calls the COM library function CoCreateInstance to create objects. I used CreateInstance rather than CoCreateInstance in my B-- examples because the real CoCreateInstance takes extra arguments that are beyond the scope of this discussion. Visual Basic does the same thing with its CreateObject function, which is simply a wrapper for COM object creation functions. This is the signature for CreateInstance:

Function CreateInstance(clsid As GUID, iid As GUID) As Object

The implementation creates the object by allocating memory for it, setting up the vtable for its method pointers, reference counting it, and raising the Class­_Initialize event. If the object is successfully created, it will have a reference count of 1 and a nonzero value (obj Is Nothing = False). A created object owns memory that was allocated with ReDim and that should be deallocated with Erase when the object is destroyed.