FAQ 34.10 What is the IUnknown interface?
class IUnknown { public: virtual HRESULT QueryInterface(REFIID riid, void** ppv) = 0; virtual unsigned long AddRef() = 0; virtual unsigned long Release()= 0; }; The IUnknown interface defines the following three methods.
The pervasive nature of this interface has a profound impact on COM. First, a COM object that has multiple interfaces may have multiple implementations of the IUnknown interface. This is because each interface is derived from IUnknown and therefore might have its own implementation of IUnknown. Second, all calls to QueryInterface for a single COM object must behave in the same manner at all times. For example, if at one point QueryInterface returns non-NULL when asked whether this COM object supports the IStack interface, then it must always return a valid interface pointer and cannot return NULL. As another example, suppose a caller has a pointer to one interface of a COM object and uses that interface pointer to call QueryInterface to ask if that object supports IStack. Then, all the other implementations of QueryInterface provided by all the other interfaces of the COM object must respond in the same manner (it would be illegal for some implementations of QueryInterface to return an interface pointer and for other implementations to return NULL). Third, in a very loose sense, QueryInterface is similar to the RTTI mechanism of C++. It is the mechanism by which a caller gains access to the other services defined by an object. Fourth, AddRef and Release point to the fact that the lifetimes of COM objects are controlled through reference counting. Thus, AddRef must be called whenever an interface pointer for a COM object is created or copied, and Release must be called whenever an interface pointer is destroyed (by the way, AddRef is called implicitly by CoCreateInstance() and QueryInterface()). Fifth, the IID for IUnknown, is called IID_IUnknown, and it is defined in the COM header files since it is a standard interface defined by Microsoft. |