Wednesday, April 6, 2016

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

0 comments:

Post a Comment