Use Pointers to Parents

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.

See also  5 Benefits of Using Time Tracking Software

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist