Parent Object for Custom Class of variable Type

Viewed 274

I'm programming quite a complex thing in VBA I think and even though I did a lot of research I couldn't come up with a solution to my problem so far. And unfortunately I'm no expert :)

I have two classes, e.g. clsBuilding and clsFactory, which both have an instance of clsHeatDemand. Now I'm trying to implement a parent-Property to access some values from the base classes I need for the calculation, based on this idea.

Friend Property Get Parent() As clsBuilding
    Set Parent = ObjFromPtr(parentPtr)
End Property
Friend Property Set Parent(obj As clsBuilding)
    parentPtr = ObjPtr(obj)
End Property

My problem now is that the parent can be of two different types even though they have the same parameters I need. So what I'm trying to ask is if there is a way to hand over the instances simply as obj As Object and still access its properties?

I also tried this with Interfaces but I would be happy if there is another easier solution.

1 Answers

I don't know if this can help you, have a look at it.

' Class which has different parent

Option Explicit

Private m_parent As Variant

Public Property Get Parent() As Variant
    Set Parent = m_parent
End Property

Public Property Set Parent(ByVal vNewValue As Variant)
    Set m_parent = vNewValue
End Property

Public Function Name()
    If TypeName(m_parent) = "ParentA" Then
        Name = m_parent.Name
    Else
        Err.Raise 123, "Parent doesn't have Name"
    End If
End Function

Public Function Height()
    If TypeName(m_parent) = "ParentB" Then
        Height = m_parent.Height
    Else
        Err.Raise 456, "Parent doesn't have Height"
    End If
End Function

' ParentA

Public Name As String

Public Age As Integer

' ParentB

Public Height As Double

Public Weight As Double

' Test

Sub test()
    Dim c As Class
    Set c = New Class

    Dim pa As ParentA
    Set pa = New ParentA
    pa.Age = 5
    pa.Name = "Parent A"

    Dim pb As ParentB
    Set pb = New ParentB
    pb.Height = 15.5
    pb.Weight = 50.5

    Set c.Parent = pa
    Debug.Print c.Name


    Set c.Parent = pb
    Debug.Print c.Height
    Debug.Print c.Name
End Sub
Related