Horje
Function Pointers and Callbacks in C++

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



Reffered: https://www.geeksforgeeks.org


C++

Related
Can We Access Local Variable&#039;s Memory Outside its Scope? Can We Access Local Variable&#039;s Memory Outside its Scope?
When to Use Virtual Destructors in C++? When to Use Virtual Destructors in C++?
How Do I Print a Double Value with Full Precision Using cout? How Do I Print a Double Value with Full Precision Using cout?
How to Sort User-Defined Types Using std::sort? How to Sort User-Defined Types Using std::sort?
How to Overload the Multiplication Operator in C++? How to Overload the Multiplication Operator in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
10