Is there a better way to call each derived object's method for a base class?
-
20-09-2019 - |
Question
I have a base class where I derive several classes. I have another class that uses all those derived classes in a different way. However, I want to call the Update()
method (inherited from the base class) on each derived class. Is there an easy way to do this, or do I have to do something like:
dim a As Derived1
a.Update
dim b As Derived2
b.Update
etc...
Solution
I think the best way to do this is to keep the derived objects in a list of some kind, and then iterate over them to call Update.
In pseudo-code:
foreach BaseClass item in {a, b, ...}:
item.Update
OTHER TIPS
You can do that through polymorphism with a function call that's passed the base class (pseudo-code):
Dim Dev1 as Derived1 '// This is derived from the class BaseClass
Dim Dev2 as Derived2 '// This is derived from the class BaseClass
CallUpdate(Dev1)
CallUpdate(Dev2)
Function CallUpdate(BaseClass bc)
bc.Update()
End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow