Pointers to functions in C++

By: Manoj Kumar Emailed: 1601 times Printed: 2051 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Just as an array name is a constant pointer to the first element of the array, a function name is a constant pointer to the function. It is possible to declare a pointer variable that points to a function, and to invoke the function by using that pointer. This can be very useful; it allows you to create programs that decide which functions to invoke based on user input.

The only tricky part about function pointers is understanding the type of the object being pointed to. A pointer to int points to an integer variable, and a pointer to a function must point to a function of the appropriate return type and signature.

In the declaration

long (* funcPtr) (int);

funcPtr is declared to be a pointer (note the * in front of the name) that points to a function that takes an integer parameter and returns a long. The parentheses around * funcPtr are necessary because the parentheses around int bind more tightly, that is they have higher precedence than the indirection operator (*). Without the first parentheses this would declare a function that takes an integer and returns a pointer to a long. (Remember that spaces are meaningless here.)

Examine these two declarations:

long * Function (int);
long (* funcPtr) (int);

The first, Function (), is a function taking an integer and returning a pointer to a variable of type long. The second, funcPtr, is a pointer to a function taking an integer and returning a variable of type long.

The declaration of a function pointer will always include the return type and the parentheses indicating the type of the parameters, if any. Listing below illustrates the declaration and use of function pointers.

Pointers to functions.

1:     //Using function pointers
2:
3:     #include <iostream.h>
4:
5:     void Square (int&,int&);
6:     void Cube (int&, int&);
7:     void Swap (int&, int &);
8:     void GetVals(int&, int&);
9:     void PrintVals(int, int);
10:    enum BOOL { FALSE, TRUE };
11:
12:    int main()
13:    {
14:       void (* pFunc) (int &, int &);
15:       BOOL fQuit = FALSE;
16:
17:       int valOne=1, valTwo=2;
18:       int choice;
19:       while (fQuit == FALSE)
20:       {
21:          cout << "(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: ";
22:          cin >> choice;
23:          switch (choice)
24:          {
25:             case 1: pFunc = GetVals; break;
26:             case 2: pFunc = Square; break;
27:             case 3: pFunc = Cube; break;
28:             case 4: pFunc = Swap; break;
29:             default : fQuit = TRUE; break;
30:          }
31:
32:          if (fQuit)
33:             break;
34:
35:          PrintVals(valOne, valTwo);
36:          pFunc(valOne, valTwo);
37:          PrintVals(valOne, valTwo);
38:       }
39:     return 0;
40:    }
41:
42:    void PrintVals(int x, int y)
43:    {
44:       cout << "x: " << x << " y: " << y << endl;
45:    }
46:
47:    void Square (int & rX, int & rY)
48:    {
49:       rX *= rX;
50:       rY *= rY;
51:    }
52: 
53:    void Cube (int & rX, int & rY)
54:    {
55:       int tmp;
56: 
57:       tmp = rX;
58:       rX *= rX;
59:       rX = rX * tmp;
60:
61:       tmp = rY;
62:       rY *= rY;
63:       rY = rY * tmp;
64:    }
65:
66:    void Swap(int & rX, int & rY)
67:    {
68:       int temp;
69:       temp = rX;
70:       rX = rY;
71:       rY = temp;
72:    }
73:
74:    void GetVals (int & rValOne, int & rValTwo)
75:    {
76:       cout << "New value for ValOne: ";
77:       cin >> rValOne;
78:       cout << "New value for ValTwo: ";
79:       cin >> rValTwo;
80: }

Output: (0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 1
x: 1 y: 2
New value for ValOne: 2
New value for ValTwo: 3
x: 2 y: 3
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 3
x: 2 y: 3
x: 8 y: 27
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 2
x: 8 y: 27
x: 64 y: 729
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 4
x: 64 y: 729
x: 729 y: 64
(0)Quit (1)Change Values (2)Square (3)Cube (4)Swap: 0

Analysis: On lines 5-8, four functions are declared, each with the same return type and signature, returning void and taking two references to integers.

On line 14, pFunc is declared to be a pointer to a function that returns void and takes two integer reference parameters. Any of the previous functions can be pointed to by pFunc. The user is repeatedly offered the choice of which functions to invoke, and pFunc is assigned accordingly. On lines 35-36, the current value of the two integers is printed, the currently assigned function is invoked, and then the values are printed again.


C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Manoj Kumar
Importing Keystore example using keytool in Java
for loop example in Java
Result Sets, Cursors and Transactions in SQL
JSP Tags for SQL to connect to a database
Using the qsort() and bsearch() functions with values - example program in C
Using qsort() and bsearch() with strings - example program in C
scanf and sscanf sample program in C
Use of {0} is required and Accessing resource bundles programmatically in Struts
Character Arrays in C
Pointers to functions in C++
atoi(), itoa() in C++
Ticker sample program in J2ME
DateFormat sample program in Java
Random class sample program in Java - nextGaussian(), nextBoolean(), nextBytes(), nextInt(), nextLong(), nextFloat(), nextDouble()
What Is a Reference in C++?

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Using cout.width() in C++
C++ Recursion function explained using Fibonacci series
Implementing Pure Virtual Functions in C++
Character String Literals in C++
Using cout in C++
Advanced if Statements in C++
Demonstrating global and local variables in C++
Dot (.) vs Arrow (->) to access data members in C++
C++ Destructors Versus Java Finalization
strlen() sample program in C++
Printing values in DEBUG mode in C++
while loop in C++
C++ keywords
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Most Emailed Articles (in C++)
Specifying default values to function parameters in C++
Nested Loops in C++
The Stack and the Free Store in C++
Calculating total based on the given quantity and price in C++
Constructors and Destructors in C++
Dot (.) vs Arrow (->) to access data members in C++
Operator Precedence in C++
qsort() sample program in C++
Getting User Input Using cin in C++
Using command-line arguments in C++
Programming errors a compiler will detect in C++
C++ keywords
Matrix using nested for loops in C++
Use of Conditional (Ternary) Operator in C++
Tutorial on Classes and Members in C++