-1
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.

Louis Langholtz
  • 2,913
  • 3
  • 17
  • 40
Thomas
  • 11
  • 1
  • 2
  • Which instance should execute `functionB` in `functionA`? Is this an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)? – Rakete1111 Aug 17 '17 at 17:06
  • 2
    Lookup _Observer Pattern_, callback functions, callback interfaces. – user0042 Aug 17 '17 at 17:06
  • I have a class (Class A) which represents the description of something that should be visualized by another Class (Class B). I want to pass Class A once to Class B. But if the description (something in Class A) is changed by a function, I want to automatically trigger the corresponding visualization function in Class B. – Thomas Aug 17 '17 at 17:13

1 Answers1

1

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.

ahnafisenough
  • 168
  • 1
  • 1
  • 8