[SOLVED] Call virtual methods from QThread::run()



  • This may be a C++ question so apologies in advance - I just couldn't google an answer (or even a variation on the question).

    I have a class subclassing QThread, and it has a pure virtual method.

    @
    class Thread : public QThread
    {
    public:
    Thread(QObject *parent);
    virtual void run()
    {
    while (true) {
    doSomething();
    }
    }
    virtual void doSomething() = 0;
    };
    @

    I have a class subclassing the above, with an implementation of that virtual method
    @
    class ThreadSub : public Thread
    {
    ThreadSub(QObject *parent)
    : Thread(parent)
    {
    }

    virtual void doSomething() {
        qDebug() << "something";
    }
    

    };
    @

    I created an instance of ThreadSub and called start(). I got an error saying "Pure virtual method called".

    This is a simplified version of the code I had but, based on what is visible here, should there be any issue?



  • And a clarification - in my full code, the constructor or destructor of the base class do not the virtual method.



  • I think it is the same problem as with the constructor. If you overwrite the run method again, it should work (but I did not try!).



  • Thanks for your comment butterface,

    But I do want my run() code to run in the base class - that's the whole point of my class-subclass separation.


  • Moderators

    The code you posted works fine, so there must be something wrong in the real code.
    It's usually a better idea to separate the thread management (QThread object) from the work itself (a QObject derived worker object). Deriving from QThread has all sorts of potential problems.



  • I ended up changing the code a lot - but if I remember correctly, this WAS eventually an issue with the destructor/constructor. Wish I had more to add but anyway it's solved.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.