0
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?

Avi
  • 71
  • 5
  • 4
    Kind of related: do not use the SIGNAL and SLOT macros in new code. Qt5 introduced connections based on function pointers, which is safer and checked at compile time. – Botje Apr 25 '23 at 06:46
  • 1
    for 2), why wait till tomorrow? You can try and see what happens today – 463035818_is_not_an_ai Apr 25 '23 at 06:53
  • 1
    Qt is helping to implement observer pattern with least code typed. It is not about polymorphism. You have to connect signal of concrete object A with slot of concrete object B for B to observe A and types of A and B (or "this" and "item" in your example) are orthogonal. – Öö Tiib Apr 25 '23 at 07:08
  • It's all implemented in the `Q_OBJECT` macro in combination with the moc generator which runs at compile time to generate the necessary metadata – Alan Birtles Apr 25 '23 at 07:10

0 Answers0