Pointers to functions in C++

In C++, just as we can have pointers to variables, we can have pointers to functions as well.

The general syntax of a pointers to a functions is:

return-type (*pointer-name) (list of parameter);

For example:

void (*p) (float, int);

In the above declaration, a pointer to a function returns void and takes the two formal arguments of float and int types respectively.

After declaring a pointer to a function, the address of the function must be assigned to a pointer as follows:

p = &function-name;

where p is a pointer variable.

Through pointer to function, the function is called as follows:

A = (*p) (x, y);

where, x and y are actual parameters, and
A is a variable in which the function’s return value is stored,
p is a pointer name which points to the function

Let us illustrate pointer to function with a programming example as follows:

#include<iostream.h>
void main()
{
   float add(float, float);   //function prototype
   float a, b, s;
   float (*p) (float, float); //declaration of pointer to function
   p = &add;                  //assigning function add to p

   a = 20.5;
   b = 10.3;
   s = (*p) (a,b);            //calling function add through pointer
                              //to function p
   cout << "s= " << s << endl;
}

float add(float a1, float a2)
{                              //add function defined
   int sum;
   sum = a1 + a2;
   return(sum);
}

The output of the above program would be:

s = 30.8

In the above program:

  • The statement:
    float (*p) (float, float);

    declares a pointer p which is a pointer to function

  • The statement:
    p = &add;

    assigns the address of function add to p, i.e., now pointer p points to function add

  • The statement:
    s = (*p) (a, b);

    calls the function which is pointed by p (i.e., add) and then assigns the returned value of function to s

  • It is worthwhile to note here that if in pointer to function declaration we skip the bracket in which pointer name is is written the C++ compiler interprets it as a function which returns a pointer type value. For example, if in above program we write:
    float *p (float, float);

    then this statement means p is a function which returns pointer and the pointer points to float type data. i.e., function returns a pointer to float

You may also like...

2 Responses

  1. fredrick says:

    Hi! I could have sworn I’ve been to this website before but after checking through some of the post I realized it’s new to me.

    Anyhow, I’m definitely happy I found it and I’ll be
    book-marking and checking back frequently!

  2. Amit says:

    Nice explanation, but Why VOID MAIN() … it can’t be accepted.

Leave a Reply

Your email address will not be published. Required fields are marked *