C++ function pointer

Like a normal variable, a function has its own address. When it is called its address is used. Therefore, you can have a pointer to point to that address. This pointer is called function pointer or pointer to function. Then you can call the function by using the pointer.
One more important use of function pointer is in the case that you want to pass a function as an argument of another function. So in that function, you can let the function being passed do thing for you.
The pointer to the function must specify the same return data type and arguments.
Data_type function_name(arg1,arg2,...);
Data_type (*pointer_name)(arg1,arg2,...);
To let the point point to the function write:
pointer_name=function_name;
Then call the function by using pointer write:
pointer_name(value1,value2,...);
or you can write:
(*pointer_name)(value1,value2,...);

In case that you pass functions as arguments of other function, you need to specify function pointers in argument list of the function. When you call that function you supply only the names of the functions.

See the example code below to clarify it.

#include <iostream>
#include <conio.h>
#include<cstring>
using namespace std;
int sum(int a,int b){
   return(a+b);
}
int subtract(int a,int b){
   return(a-b);
}
int mulr(int (*a)(int,int), int (*b)(int,int)){
   return(a(20,20)+b(90,50));
}

int main(){
   int (*p)(int,int);
   p=sum; // point to sum function
   cout<<p(10,20)<<endl; //call sum function
   p=subtract;// pointer to subtract function
   cout<<p(10,20)<<endl; //call subtract function
   //pass sum and subtract functions to mulr function
   cout<<mulr(sum,subtract);
   getch();
   return 0;
}

Posted by: Ly | post date: 01-26-2013 | Subject: C++ Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.