When trying to navigate through a complex class hierarchy from any given instance of an object, it's useful to be able to reference its parent. But how do you clean up any circular references when terminating the objects? Here is a simple way to retrieve a parent object using the undocumented ObjPtr function in VB:
' Code for clsChild Class
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" _
Alias "RtlMoveMemory" (dest As Any, source _
As Any, ByVal numBytes As Long)
Private lngParent As Long
Property Set Parent(Frm As Form)
' obtain a pointer to the object
lngParent = ObjPtr(Frm)
End Property
Property Get Parent() As Form
Dim frmobj As Form
CopyMemory frmobj, lngParent, 4
Set Parent = frmobj
CopyMemory frmobj, 0&, 4
End Property
To test the object's new Parent property, create a new form and add a button called cmdTest. Place this code in the button's Click event:
Option Explicit
Private Sub cmdTest_Click()
Dim loChild As New clsChild
With loChild
Set .Parent = Me
MsgBox .Parent.Caption
End With
End Sub
Because the child class only contains the pointer to the parent's memory, there are no circular references to resolve.