More generally, two types of polymorphism ("pseudo" or "real") are available with FreeBASIC, thanks to:
- Overloading => compile-time "pseudo" polymorphism
- Overriding => run-time "real" polymorphism
Overloading
Procedures (sub/function/operator) can be overloaded and the resolution is done thanks to the passed parameter signature (parameter type at compile-time).
The parameter passing can be explicit:
Code: Select all
Type Dog
Dim As String name
End Type
Type Cat
Dim As String name
End Type
Sub Speak Overload(Byref d As Dog)
Print "Woof! My name is "; d.name
End Sub
Sub Speak Overload(Byref c As Cat)
Print "Meow! My name is "; c.name
End Sub
Dim As Dog d : d.name = "Buddy"
Dim As Cat c : c.name = "Whiskers"
Speak(d)
Speak(c)
Sleep
or by extension implicit (hidden parameter by calling member procedure on objects):
Code: Select all
Type Dog
Dim As String name
Declare Sub Speak()
End Type
Type Cat
Dim As String name
Declare Sub Speak()
End Type
Sub Dog.Speak()
Print "Woof! My name is "; this.name
End Sub
Sub Cat.Speak()
Print "Meow! My name is "; this.name
End Sub
Dim As Dog d : d.name = "Buddy"
Dim As Cat c : c.name = "Whiskers"
d.Speak()
c.Speak()
Sleep
or mixed.
Overriding
In an inheritance structure, the override member procedure is called on an object depending on its run-time type (and not on its compile-time type which can be the same for all objects):
Code: Select all
Type Animal Extends Object
Dim As String name
Declare Abstract Sub Speak()
End Type
Type Dog Extends Animal
Declare Virtual Sub Speak()
End Type
Type Cat Extends Animal
Declare Virtual Sub Speak()
End Type
Sub Dog.Speak()
Print "Woof! My name is "; this.name
End Sub
Sub Cat.Speak()
Print "Meow! My name is "; this.name
End Sub
Dim As Animal Ptr p(1 To 2) = {New Dog, New Cat}
p(1)->name = "Buddy" : p(2)->name = "Whiskers"
p(1)->Speak()
p(2)->Speak()
Delete p(1) : Delete p(2)
Sleep
These articles I wrote in the Programmer's Guide might help about run-type polymorphism:
-
Composition, Aggregation, Inheritance
-
Inheritance Polymorphism
then, for a deeper knowledge (technical articles):
-
OBJECT built-in and RTTI info
-
Use Implicit / Overload New([]) and Delete([]) Operators with Inheritance Polymorphism