// Demonstration of class member function used to service a callback #include #include #include #include Fl_Window* mainwin; Fl_Button* but1; Fl_Button* but2; Fl_Value_Output* out1; class Counter { private: int count; public: Counter(int startvalue) : count(startvalue) {out1->value(startvalue);}; // These will be used as callback functions, but note they have to be // _static_ class functions. That is, they are not are not associated // with any particular instance of the class. static void up(Fl_Widget* w, void* o); static void down(Fl_Widget* w, void* o); }; // Implementation of the callback functions. The trick is to accept a // pointer to the the particular object via the second argument, then access // attributes of the object (like count) via this pointer void Counter::up(Fl_Widget* w, void* o) { Counter* object = (Counter*)o; object->count++; // we can reach other widgets such as out1 via their global pointers out1->value(object->count); } void Counter::down(Fl_Widget* w, void* o) { Counter* object = (Counter*)o; object->count--; out1->value(object->count); } int main() { mainwin = new Fl_Window(300,200,"Class cb"); but1 = new Fl_Button(25,25,100,25, "Up"); but2 = new Fl_Button(175,25,100,25, "Down"); out1 = new Fl_Value_Output(75,100, 100, 25, "Count"); // Here is where we create an object of the Counter class Counter mycount = Counter(5); // Since the callback functions are class static, we have to provide // a pointer to the object as the second argument. mycount is // an ordinary (non-pointer) variable, so the & operator is needed to // get a pointer to it. but1->callback(Counter::up, &mycount); but2->callback(Counter::down, &mycount); // Just for variety, here is how it would be done if mycount was a // pointer to a counter: // Counter* mycount = new Counter(5); // but1->callback(Counter::up, mycount); mainwin->end(); mainwin->show(); return Fl::run(); }