class IBase :public QObject
{
Q_OBJECT
};
class Derived :public IBase
{
Q_OBJECT
public slots:
void Init(int count)
{ //Do something }
};
class Emitter
{
signals:
void NotifyCountChanged(int);
public:
PerformOperation(QObject* item)
{
connect(this, SIGNAL(NotifyCountChanged(int)), item, SLOT(Init(int))); // Old style syntax
emit NotifyCountChanged(5); // Emitting the signal
}
};
int main()
{
IBase *pBase = new Derived();
Emitter emitterObj;
emitterObj.PerformOperation(pBase);
}
Above is a simplified version of code from my project. This code works fine i.e upon emitting the signal, the Init slot in derived class gets executed. I want to understand how this is working internally?
Here are few doubts: 1: If we compare it with normal C++ behaviour, why does it not require a pure virtual Init() method in IBase interface. We pass the QObject* pointer in PerformOperation method and use it to connect to a slot in derived class. Why does this compile even?
2: Tomorrow if I add another derived class "Derived2" deriving from IBase and add the same name slot "Init", and pass both of them to PerformOperation. Then upon emitting the signal how will QT behave. Will it execute both the slots from Derived1 and Derived2 respectively? What if I want it to work in a way that happens in runtime polymorphism i.e it executes slot of the respective Derived class only, not both
3: I know it has something to do QMetaObject, but I am not able to relate it to runtime polymorphism in C++ using virtual keyword. Is QMetaObject created for each instance of QObject subclass? For example in this case, will there be 2 QMetaObject instances created at runtime for Derived1 and Derived2 respectively?