Skip to content

Instantly share code, notes, and snippets.

@Dantali0n
Created August 15, 2017 12:16
Show Gist options
  • Save Dantali0n/0338ff14e03d54859ab3f33e8a4e66c4 to your computer and use it in GitHub Desktop.
Save Dantali0n/0338ff14e03d54859ab3f33e8a4e66c4 to your computer and use it in GitHub Desktop.
C++ Delegation in A java type fashion
#include "exampleclass.h"
/**
* Assign instance of delegate upon object construction, do not allow serialCommand to exist without a delegate object
*/
ExampleClass::ExampleClass(ExampleClassDelegate *eventHandler) {
this->eventHandler = eventHandler; // assign the delegate
}
// example function to see how calls inside of ExampleClass can reach code outside of ExampleClass
// through the instance of eventHandler/
ExampleClass::exampleFunction() {
eventHandler.eventExample(); // call eventExample to the outside of ExampleClass defined instance of ExampleClassDelegate
}
/**
* Abstract delegate to allow outside of SerialCommand processing of events
*/
class ExampleClassDelegate {
public:
virtual void eventExample() = 0;
};
class ExampleClass {
private:
ExampleClassDelegate *eventHandler;
public:
ExampleClass(ExampleClassDelegate *eventHandler);
void exampleFunction();
};
#include "exampleclass.h"
/**
* Implementation
*/
class ExampleClassDelegateImplementation: public ExampleClassDelegate {
void eventExample() {
// Code called from within ExampleCLass that is defined at a later time outside of ExampleClass
// allowing for event like behavior
}
};
ExampleClassDelegateImplementation serialCommandDelegate = ExampleClassDelegateImplementation();
ExampleClass exampleClass = ExampleClass(&serialCommandDelegate);
void setup() {
// sets of the chain of events.
// 1: ExampleClass::exampleFunction()
// 2: eventHandler.eventExample()
// 3: ExampleClassDelegateImplementation::eventExample()
exampleClass.exampleFunction();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment