Returning Other Objects By Peter Persits
Copyright (c) 1999 Persits
This articles demonstrates how to write an object which returns
another object. Our component (which we will call ParentChild) will host two
objects, Parent and Child. The Parent object will be createable via the
Server.CreateObject statement. The Child object, on the other hand, will not
have a ProgID of its own. It will be created by calling Parent's method
CreateChild, as follows:
Set Parent =
Server.CreateObject("ParentChild.Parent") Set Child = Parent.CreateChild Child.SomeMethod
CREATING THE OBJECTS
Fire up your Visual C++, go to File/New,
select ATL COM AppWizard, on the Projects tab, enter
ParentChild under Project name,
and specify a location for your poject under Location. On the next screen, accept default settings and click
Once the project has been created, go to
Insert/Insert New ATL object. Select Simple Object and click Next. In the
Short Name box, type in Parent and
accept all the default values by clicking OK. Repeat this procedure. This
time enter Child in the Short Name box. Your component now has two classes,
CParent and CChild.
Let's strip the CChild object of everything
that allows it to be created via Server.CreateObject.
1. On the ResourceView tab, delete the
IDR_CHILD registry entry under the
2. On the FileView tab, delete the
Child.rgs entry under Resource Files.
3. Open the file Child.h. Delete the
4. Open the file ParentChild.cpp. Delete
5. Open the file ParentChild.idl. Delete the
We need to add a property or method to the
Child class to make sure the Child object does indeed get created.
Right-click on an IChild node in ClassView and select "Add
Property". We will add the propery Name of the type
BSTR. Uncheck the "Put Function" checkbox to make
the property read-only, then click OK.
Open the file Child.cpp. In the body of
CChild::get_Name, insert the line
* pVal = ::SysAllocString(
right before return S_OK; Compile the project.
We are now ready to test our component with the following simple
Set Parent =
Server.CreateObject("ParentChild.Parent") Set Child = Parent.CreateChild Response.Write