Trying to do inheritance in VBA I sometimes encounter the issue of having an instance of a child class and needing to call a function from the parent's class that the child overrides.
Quick example:
In IGreeter.cls
Public Sub Greet()
End Sub
In PoliteGreeter.cls
Implements IGreeter
Private Sub IGreeter_Greet()
Debug.Print "Good morning"
End Sub
In Main.bas
Public Sub RunGreeter()
Dim MyGreeter As PoliteGreeter
Set MyGreeter = New PoliteGreeter
MyGreeter.Greet ' Doesn't work, function not defined
End Sub
There are of course easy ways to solve the issue for this example, two ways I see are:
- Define
MyGreeter
as an instance ofIGreeter
instead. - Make the override function public and call
IGreeter_Greet
directly.
Neither of these solutions are very good. For the first one, if I had additional functionality in PoliteGreeter
that I wanted to access I would need two variables to accessed its full scope of functions. The second solution is both ugly and seems very very wrong, specially since VBE by default makes the definition private.
There is however a third solution that I see and that is to add Greet
also as a public method of PoliteGreeter
as following
Implements IGreeter
Public Sub Greet()
IGreeter_Greet
End Sub
Private Sub IGreeter_Greet()
Debug.Print "Good morning"
End Sub
A fourth solution would be to do the first one and solve my concern with additional functionality through composition instead as VBA doesn't actually do inheritance. However my question is whether this third method is safe, if it shadows something, if there are caveats, and if there are other better standard solutions to this kind of problem.