Use Pointers to Parents

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 ClassOption ExplicitPrivate Declare Sub CopyMemory Lib "kernel32" _	Alias "RtlMoveMemory" (dest As Any, source _	As Any, ByVal numBytes As Long)Private lngParent As LongProperty Set Parent(Frm As Form)	' obtain a pointer to the object	lngParent = ObjPtr(Frm)End PropertyProperty Get Parent() As Form	Dim frmobj As Form	CopyMemory frmobj, lngParent, 4	Set Parent = frmobj	CopyMemory frmobj, 0&, 4End 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 ExplicitPrivate Sub cmdTest_Click()	Dim loChild As New clsChild	With loChild		Set .Parent = Me		MsgBox  .Parent.Caption	End WithEnd Sub

Because the child class only contains the pointer to the parent’s memory, there are no circular references to resolve.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: