Microsoft Office 2000/Visual Basic Programmer's Guide |
If an object contains a collection or another object, you need to create an object property that returns a reference to the object or collection that it contains. The object property should have the same name as the object or collection. For example, suppose a ParentWindow object contains a ChildWindows collection. In this case, you would create a ChildWindows property of the ParentWindow object to return a reference to that object's ChildWindows collection.
If an object belongs to another object, you may want to add a Parent property that returns a reference to the parent object. To do so, you need to define the Parent property in the class module for the child object, and set the Parent property in the class module for the parent object, after the child object has been created. For an example, see the Parent property of the ChildWindows collection in EnumWindows.xls, which is available in the ODETools\V9\Samples\OPG\Samples\CH10 subfolder on the Office 2000 Developer CD-ROM.
Important When you implement a Parent property for an object that belongs to another object or collection, you run the risk of creating circular references. A circular reference exists when a parent object maintains a reference to a child object, and the child object, through its Parent property, maintains a reference to the parent object. The problem with this circular reference is that an object is not destroyed until the last remaining reference to it is destroyed. When you attempt to destroy the parent object by setting the reference to it to Nothing, the parent object will not actually be destroyed because each of its child objects still maintain a reference to the parent object.
For example, in the EnumWindows.xls sample file, a ParentWindow object maintains a reference to its collection of ChildWindows objects through the ChildWindows object property. A ChildWindows collection maintains a reference to its ParentWindow object through its Parent property. Setting a ParentWindow object to Nothing does not destroy the reference to the ParentWindow object that is maintained by the ChildWindows collection's Parent property. To truly destroy a Parent object, you must also destroy the references maintained by the Parent property.
One way to solve the problem of circular references is to include a TearDown method on the parent object. This method should set all of the parent object's object properties to Nothing so that any references maintained indirectly through these object properties are destroyed. After you call the TearDown method on the parent object, you can set the parent object to Nothing. As long as there are no additional references to the parent object in your code, setting the parent object to Nothing will destroy the parent object in memory.