1

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?

2
  • 1
    How do you override virtual methods in derived classes? Could you show us your code, please Commented Aug 23, 2012 at 7:29
  • 1
    That is the concept of OOP, polymorphism, you don't have to check type and call appropriate method. You are at good trace, but obviously you have a bug in your implementation. Post code sample how to override virtual method draw. Commented Aug 23, 2012 at 7:31

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.