Making a QList of an abstract class objects in C++/QT? -


although i've been helped countless times other questions/answers here, first question here, don't harsh on me! :)

i've been learning qt/c++ , let's assume have this:

class abstractmasterclass{ public:     virtual void foo(void) = 0;   //pure virtual method } 

this class have plenty subclasses, each 1 of them implementing own foo() method. , question is: how can create qlist i'll populate abstractmasterclass's subclasses?

the objective able iterate through list calling foo() method every element, i.e. use master class same way java interface. few tries ended getting several compile time errors saying can't allocate object of abstract class (obviously) while creating qlist.

so how can or there better way make java interface in c++/qt?

thank in advance time answering or pointing me in right direction!

this general c++ question more qt issue. want use polymorphism in case. create pointer of type abstractmasterclass , make point 1 of derived classes, store pointers in list. used qsharedptr in example below avoid needing manual deletion of memory.

class abstractmasterclass { public:     virtual ~abstractmasterclass(){};  // virtual destructor derived classes can clean     virtual void foo() = 0; };  class deriveda : public abstractmasterclass { public:     void foo() { cout << "a\n"; } };  class derivedb : public abstractmasterclass { public:     void foo() { cout << "b\n"; } };  int main() {     qlist<qsharedptr<abstractmasterclass>> mylist;      qsharedptr<abstractmasterclass> a(new deriveda());     qsharedptr<abstractmasterclass> b(new derivedb());      mylist.push_back(a);     mylist.push_back(b);      (auto &it : mylist) {         it->foo();     }      return 0; } 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -