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:

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:

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:

The output of the above program would be:

s = 30.8

In the above program:

  • The statement:

    declares a pointer p which is a pointer to function
  • The statement:

    assigns the address of function add to p, i.e., now pointer p points to function add
  • The statement:

    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:

    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 *