0

I'm dealing with Qt + C++ (x11).

I have a base class, and several subclasses that return a new pointer to that subclass (covariant). I need to return too, an container (a QList) of these subclasses. An example:

class A
{
public:
    int id;
}

class B : public A
{
    int Age;
};

class WorkerA
{
public:
    virtual A *newOne() {return new A()};
    virtual QList<A*> *newOnes {
        QList<A*> list = new QList<A*>;
        //Perform some data search and insert it in list, this is only simple example. In real world it will call a virtual method to fill member data overriden in each subclass.
        A* a = this.newOne();
        a.id = 0;
        list.append(this.newOne()); 
        return list;
        };        
};

class WorkerB
{
public:
    virtual B *newOne() override {return new B()}; //This compiles OK (covariant)
    virtual QList<B*> *newOnes override { //This fails (QList<B*> is not covariant of QList<A*>)
        (...)
        };        
};

This will fail to compile, because QList is a completely different type from QList. But something similar would be nice. In real world, B will have more data members than A, and there will be C, D..., hence the need of "covariantate" the return of list. I will be much nicer:

WorkerB wb;
//some calls to wb...
QList<B*> *bList = wb.newOnes();
B* b = bList.at(0); //please excuse the absence of list size checking
info(b.id);
info(b.age);

than

WorkerB wb;
//some calls to wb...
QList<A*> *bList = wb.newOnes();
B* b = static_cast<B*>(bList.at(0)); //please excuse the absence of list size checking
info(b.id);
info(b.age);

Is there any way to achieve this?

Bull
  • 748
  • 1
  • 11
  • 24

1 Answers1

0

I hope from below mention code you will get some hint for this issue.

Here is main.cpp:

#include <QCoreApplication>
#include <QDebug>
#include "myclass.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyClass mClass;
    mClass.name = "Debussy";

    // put a class into QVariant
    QVariant v = QVariant::fromValue(mClass);

    // What's the type?
    // It's MyClass, and it's been registered 
    // by adding macro in "myclass.h"
    MyClass vClass = v.value<MyClass>();

    qDebug() << vClass.name;  

    return a.exec();
}
Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56