C++ function Pointers and callback function examples

  • 2020-04-02 02:23:19
  • OfStack

1. Function pointer

Function pointer is a pointer, only the pointer it is not like a normal pointer to a variable, it points to at this time is a function of its storage is the address of a function, if we change its value, make it points to the address of the point by point to funA into funB, then this function Pointers are changed.

2. Callback function

What is a callback function? A callback function is simply a function called by a function pointer! If you pass A pointer to A function as an argument to B function, and then call A function through the pointer passed in by A function in B function, this is the callback mechanism. The B function is the callback function.

3. The use of function Pointers

3.1 function pointer declaration

Typedeff return type (* function pointer type name) (function parameter list);


#include <iostream>
using namespace std;
typedef void(*Fun)(int,int); //Defines the function pointer type
void min(int a,int b);
void max(int a,int b);
void min(int a,int b)
{   int minvalue=a<b?a:b;
    std::cout<<"min value is "<<minvalue<<"n";
}
void max(int a,int b)
{   int maxvalue=a>b?a:b;
    std::cout<<"Max value is "<<maxvalue<<"n";
}
int main()
{   Fun pFun=NULL; //Define the function pointer variable pFun
    //pFun=min;  // Both assignments are supported 
    pFun=&min;
    pFun(1,2);  //I get the minimum here
    //pFun=max;
    pFun=&max;
    pFun(1,2);  //I get the maximum here
    return 0;
}


Related articles: