Function Pointers and Callbacks in C++
Last Updated :
25 Jan, 2024
A callback is a function that is passed as an argument to another function. In C++, we cannot directly use the function name to pass them as a callback. We use function pointers to pass callbacks to other functions, store them in data structures, and invoke them later. In this article, we will discuss how to use function pointer to pass callbacks in C++ programs.
Function Pointer to a Callback
To create a function pointer to any particular callback function, we first need to refer to the signature of the function. Consider the function foo()
int foo(char c) {
.......
}
Now the function pointer for the following function can be declared as:
int (func_ptr*)(char) = &foo;
This function pointer allows you to call the function foo() indirectly using func_ptr. We can also pass this function pointer to any other function as an argument allowing the feature of callbacks in C++.
C++ Program to Illustrate the Use of Callback
C++
#include <iostream>
using namespace std;
int foo( char c) { return ( int )c; }
void printASCIIcode( char c, int (*func_ptr)( char ))
{
int ascii = func_ptr(c);
cout << "ASCII code of " << c << " is: " << ascii;
}
int main()
{
printASCIIcode( 'a' , &foo);
return 0;
}
|
Output
ASCII code of a is: 97
Share your thoughts in the comments
Please Login to comment...