Using IUnknown


First you must use IUnknown every time you connect to a class. There is no Set statement in B--. There is an assignment operator, but assigning any object isn’t enough. Let’s say that you had the following code in Visual Basic:

Dim toughluck As CHardway, toobad As CHardway
Set toughluck = New CHardway
Set toobad = toughluck

Here’s how you might do the same thing:

‘’ Dim toughluck As CHardway, toobad As CHardway
Dim toughluck As CLSID_CHardway = 0, toobad As CLSID_CHardway = 0
’’ Set toughluck = New CHardway
toughluck = CreateInstance(CLSID_CHardway, IID_IHardway)
If toughluck = 0 Then GoTo ErrorHandler
’’ Set toobad = toughluck
toobad = IUnknown(toughluck).QueryInterface(IID_IHardway)
If toobad = 0 Then Goto ErrorHandler

It doesn’t look like much fun, does it?


(If the casting syntax IUnknown(object).Method looks unintelligible, just
take it on faith for now. We’ll see how Visual Basic can get a similar syntax in
“Interface casting” on page 585.


You don’t have to do any of this crap in Visual Basic. You don’t have to call the imaginary CreateInstance function to create a new instance. You don’t have to call QueryInterface to make sure your object variable actually supports the appropriate interface. You don’t have to call Release and AddRef to do reference counting.


Notice that although classes have class IDs, QueryInterface doesn’t care about them. Class IDs are a mechanism for creating objects, but once the object is created, the interface is all that counts. You can see a little more about how this works by looking at the implementation of a class in B--.