Implementing IUnknown


Visual Basic does a lot of work behind the scenes to make classes work. If you want a class to work properly in B--, you have to manage everything yourself. Here’s one possible version of the CHardway class:

‘ CHardway (CLSID_CHardway)
Implements IID_IHardway ‘ Every class implements default interface
Implements IID_IUnknown ‘ Every interface implements IUnknown
‘ Any class can implement additional interfaces
§

’ Private variables
§

Function IUnknown_QueryInterface(iid As GUID) As Variant
Select Case iid
Case IID_IUnknown
IUnknown_QueryInterface = IUnknown(Me)
Case IID_IHardway
IUnknown_QueryInterface = IHardway(Me)
‘ Case IID_IAnyOtherInterface
‘ IUnknown_QueryInterface = IAnyOtherInterface(Me)
Case Else
IUnknown_QueryInterface = 0
Exit Function
End Select
IUnknown_AddRef
End Function

’ AddRef and Release discussed later
Sub IUnknown_AddRef()
§

’ IHardway delegates to IUnknown
Function IHardway_QueryInterface(iid As GUID) As Variant
IHardway_QueryInterface = IUnknown_QueryInterface(iid)
End Function

’ The rest of the class
Property Get IHardway_Name(sNameA As String)
§

Visual Basic classes also implement the IDispatch interface to support late binding through a complicated mechanism that I don’t even want to think about, much less describe. Fortunately, this example supports only early binding.


In the QueryInterface implementation, requests for unrecognized interfaces fall through to the Else clause and fail. If the interface is recognized, an AddRef is done on the newly referenced object. We’ll see what that means shortly.


Don’t worry if this doesn’t make sense. The main point Visual Basic programmers need to know about QueryInterface is that it’s not free. Things you normally don’t know or care about are going on in the background all the time.