This article was previously published under Q173823
Note Microsoft Visual C++ .NET (2002) supports both the managed code model that is provided by the Microsoft .NET Framework and the unmanaged native Microsoft Windows code model. The information in this article applies only to unmanaged Visual C++ code.
The following steps demonstrate how to aggregate a COM object in an ATL project:
Add an IUnknown pointer to your class object and initialize it to NULL in the constructor.
Add the DECLARE_PROTECT_FINAL_CONSTRUCT macro to protect your object from being deleted if (during FinalConstruct) the internal aggregated object increments the reference count then decrements the count to 0.
NOTE: If you are using Visual C++.NET the Wizard adds this for you.
Use the IUnknown pointer you defined as the second parameter to the COM_INTERFACE_ENTRY_AGGREGATE macros. The first parameter is the IID of the interface of the inner object that you want to expose.
Override FinalConstruct() to create the aggregate.
Override FinalRelease() to release the IUnknown pointer.
If you use and release an interface from the aggregate during FinalConstruct, you should add the DECLARE_PROTECT_FINAL_CONSTRUCT macro to the definition of your class object.
Here is a sample with all four of the steps done in the class definition. This is a simple object, COutObj, which aggregates another simple object, CInnObj.