Reputation: 269
I have a number of derived classes from a base class. The base class is FormItem and derived classes are for example, InputField, Label or Button.
In the FormItem class I have a number of virtual functions such as:
internal virtual void draw(parameters) {}
This function is overloaded in each derived class.
I store objects made from the derived classes in an array list called formItems.
When I make a call like this:
((FormItem)formItems[index]).draw(parameters)
I expect the overloaded function to be called since the function in the base class is virtual. Yet, the base class's draw() method is called instead.
One rather ugly solution to this is to make a giant if statement such as this:
if (formItems[index] is Button)
{
((Button)formItems[index]).draw(parameters);
}
else if (formItems[index] is Label)
etc...
However I'm hoping that there is a better solution that doesn't need me to create this huge if-else block, but allows me to have the compiler interpret the item I'm looking at as an object of the derived class automatically and call the appropriate draw() method. Can anybody help me?
Upvotes: 1
Views: 608
Reputation: 1062650
internal virtual void draw(parameters) {}
This function is overloaded in each derived class.
I suspect that is literally true. To ensure you call the correct implementation automatically, it must be overridden in each derived class, i.e.
class Button : FormItem {
internal override void draw(parameters) { /* actual impl */ }
...
}
As long as you override
, it should work fine.
Upvotes: 3