an example of C++ function pointer that is useful in implementing functionals such as an integral


👍 g++ funcpointer.cpp && ./a.out
14
14
sum(f, 3, 8) = 66
sum(g, 1, 7) = 140
sum(sin, 3, 7) = -1.19704
👍 cat funcpointer.cpp 
#include <iostream>
#include <cmath>
using namespace std;

double f(double x) 
  { return 2 * x; }

double g(double x) 
  { return x * x; }

double sum(double(*f)(double),
           int n,
           int m) {
  double result = 0;
  for (int i = n; i <= m; i++)
    result += f(i);
  return result;
}

int main() {
  cout << f(7) << endl;
  cout << (*f)(7) << endl;
  cout << "sum(f, 3, 8) = "
       << sum(f, 3, 8) << endl;
  cout << "sum(g, 1, 7) = "
       << sum(g, 1, 7) << endl;
  cout << "sum(sin, 3, 7) = "
       << sum(sin, 3, 7) << endl;
}