Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The textbook describes function pointers in C++ as a mechanism for calling subpr

ID: 3813621 • Letter: T

Question

The textbook describes function pointers in C++ as a mechanism for calling subprograms indirectly. Write a simple C++ program that defines two different functions (f and g) that both take two int values and return an int value. Also define a function called "higher order" that takes a function as a parameter (via a function pointer with the same signature as f and g) and two int values, and then calls the passed in function over the two values, returning the result. Write a main function that outputs the result of calling the "higher order" function twice: once passing in f and once passing in g.

Explanation / Answer

#include <iostream>

/*define function f as per the question*/

int f (int x) {

return x;

}

/*define function g as per the question*/

int g (int x) {

return x;

}

/*define function higher_order taking function pointers and two integers (int (*foo)(int),int, int) as per the question*/

int* higher_order (int (*foo)(int) , int x, int y) {

  

/*declare result as int pointer for returning function call values*/

int *res = new int[2];

res[0] = (*foo) (x);

res[1] = (*foo) (y);

/*return results*/

return res;

}

int main () {

  

/*declare function pointer foo to store address of type (int function(int))*/

int (*foo)(int);

/*store address of f in foo*/

foo = &f;

  

/* call higher_order function and store result in res1 variable */

int *res1 = higher_order (foo, 2,3);

/* print results */

std::cout << res1[0]<<std::endl;

std::cout << res1[1]<<std::endl;

/*store address of g in foo*/

foo = &g;

  

/* call higher_order function and store result in res2 variable */

int *res2 = higher_order (foo, 4,5);

/* print results */

std::cout << res2[0]<<std::endl;

std::cout << res2[1]<<std::endl;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote