IUnknown* pUnknown = ...; // Assume we have a pointer to an IUnknown interface IDispatch* pDispatch = nullptr; // Assume we want to query for an IDispatch interface HRESULT hr = pUnknown->QueryInterface(__uuidof(IDispatch), (void**)&pDispatch); if (SUCCEEDED(hr)) { // Successfully obtained the IDispatch interface } else { // Query failed - the object may not implement the specified interface }
class IMyCustomInterface : public IUnknown { public: virtual void DoSomething() = 0; }; IMyCustomInterface* pCustom = ...; // Assume we have a pointer to an IMyCustomInterface interface IDispatch* pDispatch = nullptr; // Assume we want to query for an IDispatch interface HRESULT hr = pCustom->QueryInterface(__uuidof(IDispatch), (void**)&pDispatch); if (SUCCEEDED(hr)) { // Successfully obtained the IDispatch interface } else { // Query failed - the object may not implement the specified interface }In this example, we start with a pointer to a custom interface `IMyCustomInterface` that derives from `IUnknown`. We try to obtain an IDispatch interface, which is not directly supported by the object. If the object has implemented the `IDispatch` methods, the query will succeed because `IDispatch` inherits from `IUnknown`. This is called interface inheritance. The package library for IUnknown QueryInterface is the COM subsystem of Windows. It is part of the Windows SDK and is typically used in conjunction with other COM-related libraries such as ATL (Active Template Library) or MFC (Microsoft Foundation Classes).