Skip to content

Instantly share code, notes, and snippets.

@jacobmoroni
Last active February 2, 2022 16:42
Show Gist options
  • Save jacobmoroni/564fd6e2a72e4b09def8d35cdcfcc722 to your computer and use it in GitHub Desktop.
Save jacobmoroni/564fd6e2a72e4b09def8d35cdcfcc722 to your computer and use it in GitHub Desktop.
Component Callback Functions C++

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
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment