Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic Behavior in VB6

I recently noticed the CallByName keyword in VB6.

Since this takes a object, procedure name, "call type" and arguments array, can this be used to "fake" some types of polymorphic behavior?

I can make 2 classes, class A and B, each with the same method Foo, and do:

Dim list As New Collection
Dim instanceA As New ClassA
Dim instanceB As New ClassB
Dim current As Object

Call list.Add(instanceA)
Call list.Add(instanceB)

For Each current in list
  Call CallByName(current, "methodName", vbMethod)
Next

Anyone done this before? Problems? Horrible idea or genius idea? Implications? Unintended consequences?

like image 270
Tom Tresansky Avatar asked Nov 29 '22 06:11

Tom Tresansky


2 Answers

Why fake polymorphism? VB6 has real polymorphism in the form of interfaces:

' Interface1.cls '

Sub Foo()
End Sub

' --------------------------------------------- '

' Class1.cls '
Implements Interface1

Private Sub Interface1_Foo()
    ? "Hello from class 1"
End Sub

' --------------------------------------------- '

' Class2.cls '
Implements Interface1

Private Sub Interface1_Foo()
    ? "Hello from class 2"
End Sub

' --------------------------------------------- '

' Module1.mod '

Dim x As Interface1
Set x = New Class1
Call x.Foo()
Set x = New Class2
Call x.Foo()
like image 106
Konrad Rudolph Avatar answered Dec 24 '22 10:12

Konrad Rudolph


Although I agree with Mr. unicorn, I can't help but point out that CallByName is also unnecessary (in this case) because you can call the method using the standard method syntax and it will result in a late-bound (i.e. not resolved at compile-time) call:

...
For Each current In list
    Call current.methodName
Next

The real use of CallByName is to reference method names/properties where the name comes from a (possibly calculated) string value...an absolute abomination, in my opinion.

like image 41
Daniel Pratt Avatar answered Dec 24 '22 10:12

Daniel Pratt