Friday, May 25, 2012

Defining a function pointer

I wrote some simple examples how to define function pointers. Defines and initializes a function that has no arguments and no return value:
void function1() {
  std::cout << "'function1' was invoked." << std::endl;
}

int main() {
  void (*func1)() = &function1;
  func1();

  return 0;
}
Defines and initializes a function that has argument and return value:
int function2(int value) {
  std::cout << "'function2' was invoked." << std::endl;
  return value;
}

int main() {
  int (*func2)(int) = &function2;
  int value = func2(10);

  return 0;
}
Here is example how to pass a function pointer as argument:
function3(func1);
Defines an array of functions:
void (*func_array1[3])() = { func1, func1, func1 };
for (int i = 0; i < 3; i++) {
  func_array1[i](); 
}
Defines and initializes a function that refers to class member:
class MyClass {
  public:
    void myFunction(int value) { 
      std::cout << "MyClass function was invoked: " << value << std::endl;
    }
};

int main() {
  MyClass mc;
  void (MyClass::*member_func)(int) = &MyClass::myFunction;
  (mc.*member_func)(1);

  return 0;
}
Rather than declaring function pointer using the full prototype each time, it is helpful to use a typedef:
  typedef void (MyClass::*FunctionPointer)(int);
  FunctionPointer funcPtr = &MyClass::myFunction;
  (mc.*funcPtr)(2);

No comments:

Post a Comment