I want the Parent class to pass a pointer to a callback function to the child class when the child class is created. I got this working when the parent was the sketch thanks to this post:
In this example, the parent was the .ino
file, i.e. not a class but a collection of functions. This code worked fine.
However, I need to be able to make the call to the child constructor from a within a class as shown in the code below. I get I get an "invalid use of non-static member function on the line child = new Child ( handlerDispatcher );
Here is the complete code:
class Child {
public:
typedef void ( *callback_t ) ( uint8_t, uint8_t );
callback_t callback;
// Constructor
Child ( callback_t _callback ): callback ( _callback ) {}
void doCallback ( uint8_t id, uint8_t index ) {
callback ( id, index );
}
void makeCallbacks () {
doCallback ( 1, 0 );
doCallback ( 2, 1 );
doCallback ( 3, 2 );
}
};
class Parent {
public:
Child *child;
Parent () {}
void handlerDispatcher ( uint8_t id, uint8_t index ) {
( this->*callbackHandlers [ index ] ) ( id );
}
typedef void ( Parent:: *handlerPointer ) ( uint8_t );
handlerPointer callbackHandlers [ 3 ] = {
&Parent::handler1,
&Parent::handler2,
&Parent::handler3,
};
void handler1 ( uint8_t index ) { echo ( index ); }
void handler2 ( uint8_t index ) { echo ( index ); }
void handler3 ( uint8_t index ) { echo ( index ); }
void echo ( uint8_t value ) {
Serial.print ( "Got: " );
Serial.println ( value );
}
void configure () {
child = new Child ( handlerDispatcher );
}
void test () {
child->makeCallbacks ();
}
};
Parent parent;
void setup () {
Serial.begin ( 115200 );
parent.configure ();
parent.test ();
}
void loop() {}