COM Aggregation   «Prev 

Pass this into constructor

Implementing IClassFactory::CreateInstance in the inner object

A standard development practice is to have the C++ class that implements the inner COM object take in a pointer to the outer IUnknown in its constructor. CreateInstance will pass this into the constructor of the C++ class that implements the inner object. In its constructor, the COM object saves the outer object's pointer and uses it in all delegating IUnknown methods.

class CInnerCOMObj : ... { 
CInnerCOMObj(IUnknown *pOuterIUnknown) { ... }

The following pseudo-code demonstrates how the inner object class factory implements IClassFactory::CreateInstance:
class CInnerCOMObj_ClassFactory : public IClassFactory {
  /* We do not have to specify CreateInstance as virtual and __stdcall. 
  We inherit these attributes from IClassFactory. */
  HRESULT CreateInstance(IUnknown *pOuterIUnknown,REFIID riid,VOID **ppv) {
    /* first check for aggregation - i.e. is pOuterIUnknown non-NULL */      
    if (pOuterIUnknown != NULL) {
      /* now make sure they are asking for IUnknown. If not - fail the call */
      if (riid != IID_IUnknown) {
        return E_NOINTERFACE;
    /* Now create the COM object - passing the outer object's IUnknown into it. NOTE: this 
    call will work for the non-aggregated case too - i.e. when pOuterIUnknown is NULL*/
    CInnerCOMObj *pc = new CInnerCOMObj(pOuterIUnknown);
    /* Call QueryInterface in the COM object to get the caller's requested interface */
    HRESULT hr = pc->QueryInterface(riid, ppv);
    if (FAILED(hr)) {
      delete pc;
      return hr;
    return S_OK;