0

I have a base model where I have implemented the virtual members of QAbstractItemModel. I then use my base model in my project as needed by deriving new classes with specifics.

class BaseModel : public QAbstractItemModel{
    public:
        ...

    protected:
        QList<BaseItem*> list;
}

class DerivedModel : public BaseModel{
    public:
        ...
}

class DerivedItem : public BaseItem{
    public:
        ...
}

My derived model uses DerivedItem objects to store data which have some specifics that BaseItem doesn't have. They are stored in list. Methods in BaseModel uses objects in list as well.

My issues is because of this I have to type cast every time I access objects from list in the derived model. And I can't use macros like foreach.

Is there any tips or tricks I can use in this circumstance that will enable me to use macros and prevent me from type casting every time I access items from the list. Or is there another method (better practice) when making a common class to later derive from.

Thanks,

RushK
  • 525
  • 1
  • 5
  • 13

1 Answers1

1

when BaseItem has virtual methods and DerivedItem does only overwrite the existing members of BaseItem you should be able to call

foreach(BaseItem* item, list){
    item->foo();
}

because of polymorphism, item->foo() will call DerivedItem::foo() if it is of that type otherwise it will call BaseItem::foo()

Zaiborg
  • 2,492
  • 19
  • 28
  • My issue is the members of `DerivedItem` I want to call doesn't exist in `BaseItem`. `BaseItem`only has general members that's needed by `BaseModel` where `DerivedItem` has more specifics. – RushK Apr 21 '15 at 08:41
  • 1
    then you might think if the design could be improved or you cast the items as you use them. – Zaiborg Apr 21 '15 at 08:49