David
David

Reputation: 169

Using Interfaces in vba for using same function for different kind of type

Function "AddWeight" can add weight to every pet. I know that all of my animal (Inherit) have basicInfo type with same name ("data"), so I'm sure that "AddWeight" function can properly handle it.

Of course Vba will not let me to do that, I tried to declare in function title on object or variant.. nothing of them work for me.

Does anyone have a creative idea?

I don't want to write this function for every animal and I also don't find it elegant to call function like that:

Call addWeight(Max_Cat.data)

Does someone have another idea? Thanks in advance

   Type basicInfo
                name As string
                weight as integer
                height as integer
            End Type

            Type cat
                data As basicInfo
                mustacheType As String
            End Type

            Type dog
                data As basicInfo
                bark_volume as integer
            End Type

       Dim Max_Cat as cat
       Dim Buddy_Dog as dog
    .
    .   some code
    .
        Call addWeight(Max_Cat)
        Call addWeight(Buddy_Dog) 


        Public Function AddWeight(petName as object) 'not work also for petName as variant
        petName.data.weight =petName.data.weight+50

        End Function

Upvotes: 3

Views: 252

Answers (1)

Comintern
Comintern

Reputation: 22195

As mentioned in the comments, this isn't "inheritance" in the strictest sense of the word. It's more like a composite structure. If you want to represent your data using Types, the obvious solution is to just pass the member that you want to work with, i.e. the basicInfo:

Sub SomeSub()
    Dim Max_Cat As cat
    Dim Buddy_Dog As dog

    'Other stuff.
    AddWeight Max_Cat.data
    AddWeight Buddy_Dog.data
End Sub

Public Function AddWeight(animal As basicInfo)
    animal.weight = animal.weight + 50
End Function

If you really want to use interfaces, you'll need to build classes instead of types. That way you can have them implement a common interface, then use the interface as the parameter. This is probably going to give you much more robust and extensible code.

Upvotes: 1

Related Questions