This Pointer Example: Output

Function Pointers in C++

1. What is Function Pointer?

In C++, the compiler converts our source code to a transitional code called Object Code. One can see files with ‘.obj’ extension after this translation. After this the linker will merge the translated code and makes the binaries. While we run a program, the binaries load into a memory location called Code Segment. When there is a function, its first instruction set can be located at a certain memory location within this segment. In C++, we can store this starting address in a pointer variable and it is called Function Pointer.

In this example, we will write two functions. One will perform the square of a number and the other one will perform cubic of a number. Then, we will pass these functions as arguments to some other function. On the other hand, The called routine will make a call to these Square & cube by using the passed in function pointers.

2. Code Example

The below example shows how one can pass a function as a parameter to another function. First, go through this code example. Then look at the next section for the explanation of the code flow.

3. Code Explanation

  • The functions Square_it , Cube_it  will calculate the square and cubic of the provided numbers.
  • The summation will take the first parameter as a function pointer. Here, the function pointer passed as a parameter is supposed to fall under certain signature. Means, it should take long as a parameter and return a long value to the caller. The second parameter for the summation function tells when we want to end the summation series. Have a look at the syntax of passing the function pointer as a parameter long summationFn(long) . Here, summationFn  is the function pointer name.
  • The summation function will call the passed-in function for n number of times. As the parameter is a pointer to a function which can take long and return a long, it can be any function adhering to that rule. In our case, it can be Square_it or Cube_it .
  • In the program main, we called the summation function twice. The first time, we passed the address of the Square_it function. And the second time, we passed the Cube_it  function as the function pointer. The result we get in the main function is the Square summation from 1 to 4 and cubic summation from 1 to 4.

The screenshot below shows the program output:

Function Pointer Example: Output
Function Pointer Example: Output

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.