Function Pointers

Code resides in memory just as data does.  You can use pointers to point to functions just as you can use pointers to point to data.


int x = 0;//some data
int* ptr = &x;//ptr points to the address of variable 'x'

int func() { return 0; }//a function

int (*fPtr)() = &func;//a pointer to func

fPtr();//calling the function pointed to by the function pointer

We can use function pointers to allow STL functions to operate in custom ways.  Assume we have a struct:


struct Coords
{
int x;
int y;
};

and we want to sort a collection of Coords in a custom way.  We can do so by passing a function pointer into the 3rd parameter of the std::sort function (it needs to be a function with the following signature):


bool compareFunc(Coords lhs, Coords rhs);

A vector to sort:

std::vector someCoords;

 

Assuming some data was placed in someCoords, we then sort it like this:

std::sort(someCoords.begin(), someCoords.end(),compareFunc);

compareFunc must be a global function or a static member function:
struct Coords
{
int x;
int y;
static bool compareFunc(Coords lhs, Coords rhs);
};

Lastly, it is probably more efficient to pass the parameters by const reference rather than by value:

bool compareFunc(const Coords& lhs, const Coords& rhs);

Now, if we wanted to pass a function pointer into another function to do the comparison we would define the function prototype like this:
void doSort(std::vector<Coords> someCoords,
bool(*funcPtr)(const Coords&, const Coords&));

 

The body of the sort function could be as short as this:

doSort(std::vector<Coords> someCoords, bool(*funcPtr)(const Coords&, const Coords&))
{
std::sort(someCoords.begin(), someCoords.end(), funcPtr);
}

and you could call sort like this:


doSort(someCoords, compareFunc);

Useful links:

https://www.cprogramming.com/tutorial/function-pointers.html

https://stackoverflow.com/questions/1902311/problem-sorting-using-member-function-as-comparator

https://www.geeksforgeeks.org/functors-in-cpp/

 

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 )

Google photo

You are commenting using your Google 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