Search code examples
c++qtqt-signalsslot

C++: Call function of Class B when a function of Class A is called (Pointer to Class A is a Member of Class B)


class A {
  void functionA();
};

class B {
  A* A_;
  void functionB();
};

How can I automatically call functionB() in a class B instance, if functionA() is called outside of the class B instance? (Pointer to a Class A instance is member of the class B instance). I am looking for something like the SIGNAL/SLOT method in Qt.


Solution

  • One option is to use a function object as a callback. In the following example, B's constructor registers a lambda function in the A instance which will be called by A whenever functionA is called. This lambda, in turn, simply calls functionB.

    #include <functional>
    #include <iostream>
    
    class A {
    public:
        void functionA() {
            std::cout << "Function A called" << std::endl;
            if (callback_) {
                callback_();
            }
        }
    
        void setCallback(std::function<void(void)> callback) {
            this->callback_ = callback;
        }
    
    private:
        std::function<void(void)> callback_;
    };
    
    class B {
    public:
        B(A* a) : A_(a) {
            A_->setCallback([this](){this->functionB();});
        }
    
        void functionB() {
            std::cout << "Function B called" << std::endl;
        }
    
    private:
        A* A_;
    };
    
    int main() {
        A a;
        B b = B(&a);
    
        a.functionA();
    }
    

    The output:

    Function A called
    Function B called
    

    As you can see in the output, when a.functionA() is called in main, functionB is also called automatically.