0

I'm using MoSync / MAUI to create an mobile application prototype, but I'm facing a problem with the class inheritance:

The class hierarchy for the standard MAUI widgets is:

Widget
    EditBox
    Label
    ListBox
    ...

Then, because I want to add an standard behavior to all the widgets, I made an separate class to define that behavior:

class xFocusControl:
public:
    void method1() {};
    void method2() {};
    int member1; 
    ....

and subclass each widget type:

class xEditBox: public xFocusCtrl, public EditBox 
{
public:
    ...
}

class xLabel: public xFocusCtrl, public Label 
{
public:
    ...
}

...

Then, in several places I need to access to all the widgets using the MoSync getChildren() function, defined as:

const Vector<Widget*>& MAUI::Widget::getChildren()

My problem is: given this hierarchy, I can iterate over all the childrens as but cannot access to the new behavior (e.g: widget->member1) without casting. But, how can I generically cast each widget to its class? So far, I'm testing each possible widget class with some code like

member1 = 0;
if (isType <xLabel*> (widget)) {
    member1 = ((xLabel*) (widget))->member1; 
}

if (isType <xEditBox*> (widget)) {
    member1 = ((xEditBox*) (widget))->member1; 
}
...

but it looks bad to me: I'm a C++ newbie, and much more proficient in dynamic languages as Python, so maybe I'm taking a wrong approach.

Do you mind a better way to do this?

As noted in the comments, I'm using regular cast instead of dynamic_cast because MoSync don't supports dynamic_cast so far

PabloG
  • 25,761
  • 10
  • 46
  • 59
  • i find your way good. but use dynamic_cast thats better. As far as i know there is no way around casting. There would be virtual functions and so on but dont help in your problem. Casting is the desired way. You could write your own getWidget function and store all witdgets somewhere in a class. As far as i know multiple inheritance is bad maybee you could avoid that as well.. – Gabriel Jul 28 '12 at 23:22
  • @Gabriel: but how can I avoid multiple inheritance? I cannot modify the base class (Widget) because it's defined in the MoSync::MAUI library. Is there a way to inject the new code in the original class without subclassing? – PabloG Jul 29 '12 at 13:36

1 Answers1

1

You should use dynamic_cast

xLabel* label = dynamic_cast<xLabel*>(widget);
if (label)
{
    member1 = label->member1;
}
// dynamic cast failed
else
{
}
ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • dynamic_cast isn't available on MoSync, but anyway, should I try to cast *ANY* posible widget type manually? – PabloG Jul 28 '12 at 23:16
  • @PabloG in such case (we have objects of base_class and have no information about which type is this object and we can't change architecture of hierarchy) casting is only one possible way. – ForEveR Jul 28 '12 at 23:24