Instantiating ComObjects - best practice
My question is about the recommended way to initialising ATL interface
implementations (i.e. ComObjects) with values.
At the moment my programs are littered with code like the following:
IMyInterface pFace;
CComObject<CMyObject> *pObj;
hr = CComObject<CMyObject>::CreateInstance( &pObj );
if(SUCCEEDED(hr)) // Perform implementation-specific initialisation
{
pObj->AddRef();
hr = pObj->Initialize( some stuff specific to implementation );
if (SUCCEEDED(hr))
{
hr = pObj->QueryInterface( __uuidof(IMyInterface), &pFace );
}
pObj->Release();
}
pFace->InterfaceMethod1();
pFace->InterfaceMethod2();
....
where Intialize() is a public method of CMyObject but is no in the
interface IMyInterface. This seems to be a common patter to work around
ATLs inability to take constructor arguments.
I've also seen people do this which looks a little cleaner:
CComPtr<IMyInterface> spFace;
hr = spFace.CoCreateInstance( __uuidof(CMyObject) );
if (SUCCEEDED(hr))
{
static_cast<CMyObject *>(spFace.p)->Initialize( some imp-specific );
}
spFace->InterfaceMethod1();
spFace->InterfaceMethod2();
....
Is the second way in any way inferior to the first and are there any
other ways or recommended practices for how this should be done?
Thanks.
Alex Lamaison