Queued invoke on virtual slot in constructor
Good or evil?
For several of my objects, I need to perform some initial updates asynchronously, after the constructor has already run.
The objects share a base class, and to ensure that no derived class forgets about the asynchronous initialization step, I do like this:
class AbstractBase : public QObject
AbstractBase(QObject* parent = 0)
QMetaObject::invokeMethod(this, "doInitialUpdate", Qt::QueuedConnection);
virtual void doInitialUpdate() = 0;
The questions is:
Will Qt resolve the function pointer synchronously (within the constructor), thereby calling the pure virtual function of AbstractBase?
Or will it rather wait until the event queue ran, and then resolve the function name to the slot of the correct derived class?
Is this behavior specified and can I depend on it?
Why don't you try and see? A simple debug statement in your re-implemented doInitialUpdate() methods will tell you exactly what is happening...
There is a difference between "it works now, maybe by chance, maybe depending on Qt version/compiler/OS/whatnot" and "it is supposed to work according to standard/documentation/etc."
I could however look into the Qt source code, that's and option.
Ok, point taken.
It will work. Line 8 in your code above will result in an event being posted in the event loop. The object for that will be a QObject, I think, but certainly not AbtractBase or whatever is derived of that. Then, the event is taken of the event queue again the next time the queue is processed, and translated back to a slot invocation. Because your slot is a virtual method, only at the invokation of the method it will be decided (by the C++ mechanism for that) which method to call.
Thank you, Andre.