I was looking for a way of adding custom event handlers as a c++ class member function. Found that this code actually works.
I need to separate library class and user code, allowing user code to customize library class.
Here is concept of code. Is it correct to do so? Thread safeness is out of scope in my question. Compiler is gcc.
User code is very very neat. no inheritance, virtual functions, templates used
#include <stdio.h>
typedef void fn();
class aaa
{
public:
aaa() : customhandler(NULL) {}
fn *customhandler;
};
// user code start
void dostuff() {
printf("doing stuff 1\n");
}
void dostuff2() {
printf("doing stuff 2\n");
}
int main()
{
aaa aaa1;
aaa1.customhandler = &dostuff;
aaa1.customhandler();
aaa1.customhandler = &dostuff2;
aaa1.customhandler();
}
I tried your code and it works fine.
Just for your information, there is another way to code your function pointer. In which case your code can be simplified just a little. Here I use a slightly different syntax for the typdef for the function pointer, which lets you drop the & symbols.
Both ways are just fine, I just thought I’d show you another way to do this.