Pointers to Functions in C++
In this tutorial, we will learn about pointers to functions in C++, why we use pointers in functions. Let us see with some examples.
Pointers to functions in C++
A pointer to a function contains the address of a function and you can call the function through the pointer. You declare a Function pointer using this format:
int(* fptr)();
The pointer’s name is fptr. This particular pointer points to functions that return int accept no arguments. The pointer declaration must match those of the functions which it points.
To assign the address of a function to a function pointer, use one of these two idioms:
fptr =&TheFunction;
fptr =&TheFunction;
The & address-of operator is not required because a function’s identifier alone signifies its address rather than a call to the function, which would include an argument list in parentheses following the identifier.
You call a function through its pointer using one of these formats:
x =(*fptr)();
x=fptr();
One example of a finite state machine is a table-driven menu manager like this.
// --a menu structure struct Menu { char * name; void (*fn)(); }; // --menu selection functions void FileFunc(); void ExitFunc(); // -- the menu Menu menu[]={{"File",FileFunc},{"Exit",ExitFunc) }; // -- call through function pointer; (*menu[sel].fn)();
Functions Pointers in C++:
#include<iostream> using namespace std; void FileFunc() { cout<< "File Function \n:"; } int main() { void (*funcp)(); //Pointer to function funcp = FileFunc; //Put address in pointer (*funcp)(); //Call the function }
Output:
File Function
Program:
#include<iostream> using namespace std; struct Menu { char* name; void (*fn)(); }; void FileFunc() { cout<<"File Function\n"; } void ExitFunc() { cout<<"Exit Function\n"; } Menu menu[]={{"File", FileFunc},{"Exit", ExitFunc}}; //The menu int main() { // --- the menu manager unsigned sel =0; const int sz = sizeof menu / sizeof(menu); while(sel!=sz) { for(int i=0;i<sz ; i++) // Display the menu cout<<i+1<<" : "<<menu[i].name<< "\n"; cout<<"Select : "; cin>>sel; //Prompt for and get selection if(sel < sz+1) // -call through function pointer (*menu[sel-1].fn)(); //Call through function pointer } }
Output:
1: File 2:Exit Select : 1 File Function 1: File 2:Exit Select : 2 Exit Function
Also read:
Leave a Reply