What’s The Use Of Function Pointers In C++?

1 mainWhen we talk about C++ programming, functions and pointers are very important. A function is basically a series of steps packaged into a nice unit. A pointer is an object that refers to a value stored in memory. So why not just combine them and create something really useful! Function pointer is exactly what you think it is. A function pointer is a variable that stores the address of a function. We can call this function using the function pointer. But why would we want to do that? This looks like a roundabout way of doing things, right? What’s the purpose of having it in the first place?  

Why do we need it?

After reading the previous paragraph, you might wonder why anyone would need function pointers. If you want to call a function, why don’t we just call the function directly instead of calling it through a function pointer? Well, that’s true for most cases. But there are several other cases where function pointers are useful. Let’s say that you want to sort an array. It’s a pretty simple operation, and perhaps one of the most popular programming tasks. We can sort an array in either ascending or descending order. Regardless of that, the basic structure of the sorting process will remain the same. But as you can see here, we need to write two different functions to sort a given array, one for ascending order and one for descending order. Now what if I want to avoid writing two different functions? In our example, we need the freedom to decide whether the array is sorted in ascending or descending order.

2 sortingLet’s see how the sorting algorithms work in general. Different algorithms have different complexities and performances, but the general idea is the same. The algorithm walks through the list of given numbers, does comparisons on pairs of numbers, and reorders them based on the results of those comparisons. So technically, we can change the way we sort the numbers by varying the comparison function without affecting the rest of the sorting code. We would like to choose different behaviors at different times in essentially the same piece of code. This is where function pointers come in handy.

How do we use it?

Let’s consider the following piece of code:

int getSum(int x, int y)
{
    return x+y;
}

int getDiff(int x, int y)
{
    return x-y;
}

int main()
{
    int (*pGetSum)(int, int) = getSum;
    int (*pGetDiff)(int, int);
    pGetDiff = &getDiff;
    return 1;
}

The function getSum() takes two integers as input arguments and returns the sum. In the main() function, pGetSum is a pointer to the function getSum(). We can also just assign a function address to a function pointer, like we do for the function getDiff(). It is important that the signature of the function pointer matches with that of the function. As you can see, the function pointer takes two integer arguments and returns an integer. Now, if we want to call the function using the function pointer, we can just do this:

cout << (*pGetSum)(5,7) << endl; // calling the function getSum through pGetSum

cout << pGetDiff(5,7) << endl; // this is okay too; notice that the '*' is not necessary

As you can see here, using the ‘*’ is optional.

Is that all there is to it?

The piece of code we saw just now was just a demonstrative example. Now, let’s look at an interesting application of this concept. Consider the following piece of sorting code:

void mySort(vector<int> &input)
{
    for (int startIndex= 0; startIndex < input.size(); startIndex++)
    {
        int bestIndex = startIndex;

        for (int currentIndex = startIndex + 1; currentIndex < input.size(); currentIndex++)
        {
            // We are doing user-defined comparison here
            if (input[currentIndex] < input[bestIndex])
                bestIndex = currentIndex;
        }
  
        swap(input[startIndex], input[bestIndex]);
    }
}

The above sorting algorithm is called selection sort. As you can see here, the comparison operation is fixed. We check only one condition and it will sort the array in ascending order. We want the caller to be able to decide how the sorting will be done. So instead of using our own hard-coded comparison function, we’ll allow the caller to provide his own sorting function. This is done using a function pointer.

How do we use the function pointer?

Given that the caller’s comparison function is going to compare two integers and return a boolean value, a pointer to such a function would look something like this:

bool (*pMyComparator)(int, int);

So, we’ll allow the caller to pass a pointer to their desired comparison function as the third parameter, and then we’ll use the caller’s function to do the comparison. Here’s a full example of a selection sort that uses a function pointer parameter to do a user-defined comparison, along with an example of how to call it:

void myCustomSort(vector<int> &input, bool (*pMyComparator)(int,int))
{
    for (int startIndex= 0; startIndex < input.size(); startIndex++)
    {
        int bestIndex = startIndex;

        for (int currentIndex = startIndex + 1; currentIndex < input.size(); currentIndex++)
        {
            // We are doing user-defined comparison here
            if (pMyComparator(input[currentIndex], input[bestIndex]))
                bestIndex = currentIndex;
        }

        swap(input[startIndex], input[bestIndex]);
    }
}

// A comparison function to sort in ascending order
bool AscendingOrder(int x, int y)
{
    return x < y;
}

// A comparison function to sort in descending order
bool DescendingOrder(int x, int y)
{
    return x > y;
}

// This function prints out the values in the given array
void printArray(vector<int> &input)
{
    for (int i=0; i < input.size(); i++)
        cout << input[i] << " ";

    cout << endl;
}

int main()
{
    vector<int> inputArray = { 4, 7, 1, 5, 8 };

    // Sort the array in ascending order using the original mySort function
    mySort(inputArray);
    printArray(inputArray);

    // Sort the array in descending order using the function pointer
    myCustomSort(inputArray, DescendingOrder);
    printArray(inputArray);
    
    return 1;
}

As we can see, this code is a lot cleaner as compared to hardcoding the functionality into the sorting function. We can use a function pointer to hook our own functionality into something we’ve previously written and tested. This helps us facilitate code reuse, and it’s more efficient. Previously, if you wanted to sort one array in descending order and another in ascending order, you’d need multiple versions of the sort routine. Now you can have one unified version that can sort any way we want. Pretty neat!

——————————–—————————————————————–

3 thoughts on “What’s The Use Of Function Pointers In C++?

  1. I was recommended this blog through my cousin.
    I am now not positive whethber this put up is written by means of him as nobody else recognize such special about my problem.
    You aree amazing! Thanks!

  2. Hola! I’ve been following your weblog for some time now and finally
    got the bravery to go ahead and give you a shout out from New Caney Texas!
    Just wanted to tell you keep up the good job!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s