Adding a Parent Property to Classes
Many Microsoft-generated objects have a Parent property. This property generally provides a reference back to the parent of an object in a hierarchy. You can emulate this behavior in your own classes. Place this code in the child class:Private mobjParent As Order
Public Property Get Parent() As Order
'Return the pointer stored in mobjParent
Set Parent = mobjParent
End Property
Public Property Set Parent(ByVal objParent As Order)
If mobjParent Is Nothing Then
Set mobjParent = objParent
End If
End Property
Code in the Initialize event of the parent class sets the Parent property of the child class. The code looks like this:Private Sub Class_Initialize()
Set OrderDetail = New OrderDetail
Set OrderDetail.Parent = Me
End Sub
After the Initialize event of the Order class sets the Parent property of the OrderDetail class, the Property Set for the Parent property of the OrderDetail class executes. If the mobjParent variable is Nothing, a Set statement points the mobjParent variable at the reference to the parent class (Set OrderDetail.Parent = Me). Notice the Set statement executes only if mobjParent is Nothing. This renders the property as write-once. The following code illustrates how the Parent property is used:Sub FindParentsName()
'Declare and instantiate the Order object
Dim objOrder As Order
Set objOrder = New Order
'Retrieve Name property of the parent
MsgBox objOrder.OrderDetail.Parent.Name
End Sub
This code declares and instantiates the Order object. The Initialize event of the Order object instantiates the OrderDetail object, and sends it a reference to the Order object. The code retrieves the Name property of the Parent object and displays it in a message box.