Apart from calling the function based on its name, we could invoke a function through a function pointer which hold the function addresses. So, what makes function pointer interesting in C++? Well, there are reasons why it’s being utilized. For instance, you could invoke the export functions in a binary file by getting the address of the function. If you wish to implement a callback function in your C++ project, function pointer will definitely a recommended lesson you should learn. I will cover the callback function in upcoming article. If you wish to take a look of how you could invoke the export functions in a binary file by getting the address of the function, please refer to Exporting C++ Functions from DLL. Function pointer variable and function have identical structure. The following example illustrate how a function pointer is declared. return-type (*variable name)(arguments) Ok. It’s time to do a little bit of demonstration now. Let’s create a win32 console application now. Let’s create 2 function which will be invoked by the function pointer in our example.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*  This function will only take 1 char pointer
 *  argument.
 */

void AcceptText(char * pMsg)
{
  printf("Message : %s\n", pMsg);
}

/*  This function will take 2 integer argument.
 *  It will return the sum of 2 integer argument.
 */

int Count(int a, int b)
{
  return a + b;
}
Now we will declare a function pointer in the main entry point function and invoke its appointed function accordingly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
int _tmain(int argc, _TCHAR* argv[])
{
  //TEST1

  // Declare a function pointer variable
  void (*MsgPtr)(char *);

  // Make sure that our function pointer
  // the point to correct function
  MsgPtr = AcceptText;

  // Invoke the function by passing a char string
  MsgPtr("message");


  //TEST2

  // Declare a function pointer variable
  int (*IntPtr)(int, int);

  // Make sure that our function pointer
  // point to correct function
  IntPtr = Count;

  // Invoke the function by passing a char string
  int total = IntPtr(1,2);

  printf("Total = %d\n", total);

  return 0;
}
c++ function pointer example FuncPtr.zip