Component Callback Functions - jacobmoroni/ubuntu_hacks GitHub Wiki

Call a function in a parent or different child(component) of the parent from one of its children(component)

In the child class

class ChildClass {
public:
  void whateverFunction(int whatever_args) {
    // Set the data that will be passed into the callback
    DataType data = "whatever"; 
    if (event_handler_) {
      // indirectly call other_class->handlingFunction(data) with this line
      event_handler_(data);
    }
  }
   
  // Function pointer set externally
  void setEventHandler(std::function<void(const DataType&)> callback) { event_handler_ = callback; }
  
protected:
  std::function<void(const DataType&)> event_handler_;
}

In the parent class constructor:

ParentClass() {
  child_class->setEventHandler([this](const DataType& data) {
    other_class->handlingFunction(data);
  });
}

In the other class:

class OtherClass {
public:
  void handlingFuntion(const DataType& data) {
    //Do something with the data passed from ChildClass
  }
}