Creating QList objects of an abstract class in C ++ / QT?

although countless times have helped me on other questions / answers here, this is my first question here, so don't be too hard on me! :)

I studied QT / C ++ and suggested that I have something like this:

class AbstractMasterClass{
public:
    virtual void foo(void) = 0;   //Pure virtual method
}

There will be many subclasses in this class, each of which implements its own foo () method. And the question is: how can I create a QList that I will populate with subclasses of AbstractMasterClass?

The goal is to be able to iterate over the list calling the foo () method for each element, i.e. use the master class in the same way as for the Java interface. In several attempts, I received several compile-time errors, stating that we cannot allocate an abstract class object (obviously) when creating a QList.

So how can I do this, or is there a better way to make a Java interface in C ++ / QT?

Thanks to everyone in advance for answering or pointing me in the right direction!

+2
source share
1 answer

This is a general C ++ question, not a Qt question. In this case, you would like to use polymorphism. Create a pointer of type AbstractMasterClass and point it to one of your derived classes, then save the pointers in your list. I used QSharedPtr in the example below to avoid having to manually delete the memory.

class AbstractMasterClass {
public:
    virtual ~AbstractMasterClass(){};  // virtual destructor so derived classes can clean up
    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);

    for (auto &it : myList) {
        it->foo();
    }

    return 0;
}
+3
source

All Articles