- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming
How to Create an Array of Function Pointers in C++
In C++ functions can be called through arrays if we initialize an array of pointers and direct each of these pointers to our desired function.
There are however three conditions for an Array of function pointers to work:
You should notice in the example code below that all of the three functions have same arguments and return types, they may be used to perform different operations however.
#include <iostream> using namespace std; //function prototypes -- each function performs similar actions int Sum( int ); int Product( int ); int Cube( int ); int main() { //initialize array of 3 pointers to functions that each //take an int argument and return void int (*array[ 3 ])( int ) = { Sum, Product, Cube }; int variable; cout << "Enter a number between 0 and 2, Enter 3 to end: "; cin >> variable; // process user's choice for( int x=0 ; ( variable >= 0 ) && ( variable < 3 ) ; x++ ) { //invoke the function at location choice in //the array 'array' and pass variable as an argument (*array[ variable ])( variable ); cout << "Enter a number between 0 and 2, Enter 3 to end: "; cin >> variable; } cout << "Program execution completed." << endl; system("pause"); } int Sum( int a ) { cout<<"You entered " << a << " so Sum was called\n\n"; } int Product( int b ) { cout<<"You entered " << b << " so Product was called\n\n"; } int Cube( int c ) { cout<<"You entered " << c << " so Cube was called\n\n"; }
Explanation
Line 1-8: Pre-processors and function prototypes, guess you already know all this stuff.
Line 14: Initializes an Array of Pointers.
- Name of the array is 'array'.
- All pointers in the array are of type int because the declared functions are also of type int.
- Array contains 3 pointers.
- The second brackets indicates that all the functions to which the pointers point have one single int argument.
- Next curly brackets is the usual way of assigning values to variables of the array. Here addresses of each of the three functions are assigned to pointers in the array using this usual method.
Line 18: Asks user to enter the value of an int variable 'variable' which was initialized in line 15.
Line 21-28: Initiates a For loop to process user's choice.
Line 25: Calls that specific function to which the entered choice refers, the next bracket passes the same choice as an int argument to the function being called.
Line 27: Asks the user to re-enter the choice for the next execution of the loop.
Line 34-47: These are the functions which are being called using the array.
Usage Ideas
- Can be used to call functions using loops.
- Can be used where you want to process the same argument by many different functions.
- In the same way it can be used where you intend to pass many different arguments to the same function.