Open In App

Function Pointers and Callbacks in C++

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to illustrate how to use the callback
// function
#include <iostream>
using namespace std;
  
// callback function
int foo(char c) { return (int)c; }
  
// another function that is taking callback
void printASCIIcode(char c, int(*func_ptr)(char))
{
    int ascii = func_ptr(c);
    cout << "ASCII code of " << c << " is: " << ascii;
}
  
// driver code
int main()
{
  
    printASCIIcode('a', &foo);
    return 0;
}


Output

ASCII code of a is: 97

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads