The textbook describes function pointers in C++ as a mechanism for calling subpr
ID: 3813804 • 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>
using namespace std;
// return sum of a and b
int f(int a, int b)
{
return a+b;
}
// return multiplication of a and b
int g(int a, int b)
{
return a*b;
}
// take a function pointer and two argument and return result of that function on two arguments
int higherOrder(int (*funct)(int a, int b), int x, int y)
{
return funct(x, y);
}
int main()
{
int (*funcPointer)(int, int);
// Assigning f to funcPointer
funcPointer = &f;
cout << "Call to higher order with f and 5, 6 results in " << higherOrder(funcPointer, 5, 6) << endl;
// Assigning g to funcPointer
funcPointer = &g;
cout << "Call to higher order with g and 5, 6 results in " << higherOrder(funcPointer, 5, 6) << endl;
return 0;
}
Output
Call to higher order with f and 5, 6 results in 11
Call to higher order with g and 5, 6 results in 30
Please rate positively if this answer your question. Comment if something is not clear
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.