Pointers to functions

C programmers used pointers to functions to accomplish many of the things we do in C++ using the object-oriented mechanisms. Pointers to functions are still used though.

A simple example demonstrating how pointers to functions are used, finds the high and the low in a list of student grades.

The task of finding the high and the low is identical except when you compare, one must ask if the grade you are currently considering is higher than the highest found so far:
   if (current student's grade > highestGrade) {
      save current student's grade as the highest
   }

   if (current student's grade < lowestGrade) {
      save current student's grade as the lowest
   }
We can use the same function if we pass in a pointer to the function that will either do a greater than or a less than. First, write the bool functions that will either compare for greater than or for less than:
bool lessThan(int num1, int num2) {
   return num1 < num2;
}

bool greaterThan(int num1, int num2) {
   return num1 > num2;
}
The calls to finding the high or low, function called findExtreme, take three things:
    1. myClass which is an array of Student structs where each struct (think object) has a name, ID, and grade
    2. size which is the number of valid students in the myClass array
    3. either the greaterThan or lessthan function pointer
      int high = findExtreme(myClass, size, greaterThan);
      int low = findExtreme(myClass, size, lessThan);
The findExtreme uses the function passed in to do the correct compare in the array. Notice the syntax of the pointer to function parameter. The parameter's identifer name is compare . The asterisk says it's a pointer. Parens are needed so the asterisk goes with the correct thing. The following (int,int) shows the number of parameters and their types that compare takes.
int findExtreme(const Student myClass[], int size, bool (*compare)(int,int)) {
   int extreme = myClass[0].grade;
   for (int i=0; i < size; i++) {
      if ((*compare)(myClass[i].grade, extreme))
	 extreme = myClass[i].grade;
   }
   return extreme;
}