Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vishnumaiea/308f1f1317a395c14554efd216853275 to your computer and use it in GitHub Desktop.
Save vishnumaiea/308f1f1317a395c14554efd216853275 to your computer and use it in GitHub Desktop.
This example shows how you can pass a member function to a global function as a pointer.
//-------------------------------------------------------------//
#include <iostream>
using namespace std;
//-------------------------------------------------------------//
//the type of the callback
typedef void (*func)(void); //the only pointer type the global accetps
//-------------------------------------------------------------//
//forward declarations
class wish;
wish* wishPtr[3] = {0}; //pointer to the object
int objCount;
//-------------------------------------------------------------//
//the library function that accepts a callback
void saySomething(func say) {
say(); //invokes the member function explicitly
}
//-------------------------------------------------------------//
//one function for each object
void func_1();
void func_2();
void func_3();
//save the function ptrs to an array so that they can be automatically accessed
func funcPtr[3] = {func_1, func_2, func_3};
//-------------------------------------------------------------//
//main class
class wish {
public:
int number; //just a variable to identify the object
func callback;
//constructor
wish(int n) {
number = n;
callback = funcPtr[objCount]; //get a copy of global callback function
wishPtr[objCount++] = this; //save the object pointer so the callback can access
}
void wishSomething() {
saySomething(callback); //send the callback
}
};
//-------------------------------------------------------------//
//each function knows the object they want to point to
void func_1() {
if(wishPtr[0] != 0) {
cout << "Foo " << wishPtr[0]->number << "\n";
}
}
void func_2() {
if(wishPtr[1] != 0) {
cout << "Bar " << wishPtr[1]->number << "\n";
}
}
void func_3() {
if(wishPtr[2] != 0) {
cout << "Baz " << wishPtr[2]->number << "\n";
}
}
//-------------------------------------------------------------//
//instantiate three objects
wish A(10);
wish B(11);
wish C(12);
//-------------------------------------------------------------//
int main() {
A.wishSomething();
B.wishSomething();
C.wishSomething();
return 0;
}
//-------------------------------------------------------------//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment