OOPortal OOPortal

COM Aggregation   «Prev 

Nondelegating and delegating IUnknown

The following code fragments demonstrate how to add a nondelegating IUnknown into a COM object implementation that uses multiple inheritance. Assume that the outer object's IUnknown pointer is passed into a constructor of CCOMObj.

//Specify interface IA
class IA : public IUnknown {
  virtual HRESULT __stdcall A1() = 0;

//Specify interface IB
class IB : public IUnknown {
  virtual HRESULT __stdcall B1() = 0;

Specify a standalone IUnknown interface to be the non-delegating IUnknown. Its methods must use different names to avoid name conflicts with the IUnknown methods in other interfaces. This is OK since COM calls are based on vtable position and not names. Don't inherit from IUnknown. Doing so will force the method names to be QueryInterface, AddRef, and Release.
class INonDelegatingIUnknown {   
 virtual HRESULT __stdcall objQueryInterface
 (REFIID riid, VOID **ppv) = 0;
 virtual ULONG __stdcall objAddRef() = 0;
 virtual ULONG __stdcall objRelease() = 0;

class CCOMObj : INonDelegatingIUnknown, IA, IB {
  ULONG m_refcnt;
  IUnknown *m_pIOuterIUnknown;
  //INonDelegatingIUnknown methods
  HRESULT objQueryInterface(REFIID riid, VOID **ppv);  
  ULONG objAddRef();
  ULONG objRelease();
  //IUnknown methods for IA and IB
  HRESULT QueryInterface(REFIID riid, VOID **ppv);
  ULONG AddRef();
  ULONG Release();
  //IA methods
  //IB methods
  /* Assume that the outer object's IUnknown pointer 
	is passed into the constructor */
  CCOMObj(IUnknown *pOuter) : m_refcnt(0), 
	m_pIOuterIUnknown(NULL) {
    m_pIOuterIUnknown = pOuter;