Programmers can find the address of any named component in a C++ program, including functions, and save the address in a pointer variable. This section demonstrates function pointers with a programming construct called a callback function. In this context, programs pass one function as an argument to another. The callback architecture requires three functions, each playing a distinct role. The following figure outlines the functions, naming each after its specific role.
The three functions in the callback architecture.
The following sections further detail and demonstrate this syntax.
callback: The callback function, often defined in the client program.
supplier: The function receiving the callback function as a parameter and providing a service to the client. Defining the function parameter cb (highlighted in gold) is often the most challenging part of creating a callback system. Fortunately, the definition is embedded in the supplier function's definition, which is often a library function that hides the complexity from most application programmers.
client: The function passing the callback function and an argument, thereby requesting some service. Calling supplier passes the address of callback to the parameter cb.
It's convenient for programmers to divide callback functions into two categories. This section describes and demonstrates asynchronous callback functions. The strings chapter, later in the text, illustrates synchronous callback functions with the qsort and bsearch example programs.
Specifying Function Pointer Parameters
callback, entry point, function pointer, function address, supplier, function call operator
A function's name represents its address or entry point (the address of the first machine instruction executed when a program calls the function). Consequently, finding the function's address is a trivial operation: it's just the name of the function (without the function-call parentheses or the address-of operator). Similarly, calling the passed function is straightforward: use the parameter name in place of the original function name. Conversely, defining the parameter that receives the function's address is more challenging because it must include the function's return type and the number and type of each parameter. The compiler needs this type information to validate that the call is syntactically correct.
Prerequisite Concepts
Generalized Function Pointer Parameter
C++ syntax uses asterisks to define pointer variables:
char* name;
Function prototypes consist of the function's name, its return type, and a parentheses-enclosed parameter list
A function's name is its address or entry point
C++ implements function calls with the function call operator, parentheses that operate on the function's address:
function();
function(argument-list);
x = function(argument-list);
(a)
(b)
Understanding function pointer parameters.
Specifying a function pointer parameter requires typing information: the original function's return type and the type of each parameter, making the parameter more complex than a simple pointer.
Four distinct C++ concepts that merge in the creation and use of callback functions.
On the supplier side, the name of the callback function appears in two places: the supplier header (the prototype and definition) and the function calls.
Header: Specifying function pointer parameters requires two pairs of parentheses. Although the characters are the same in both pairs, the operators they represent are different. C++ uses the asterisk to define a pointer variable, but its precedence is lower than the function call operator (the red parentheses). Consequently, the specification must enclose the asterisk and function name in grouping (black) parentheses to change the evaluation order, making the text in the green (outer) parentheses the supplier's single parameter. The return type and parameter types in the callback's specification must match the original function's signature.
Calls: The function call operator (the red parentheses) operates on an address (denoted, in this example, by the name of a function), jumping to it and executing the machine instructions located there.
A Callback Example: The atexit Library Function
callback, atexit, exit, supplier, client, function pointer
The atexit function implements a supplier that can register 32 or more asynchronous callback functions (the exact number depends on the implementation). The C++ runtime system automatically runs the callback functions in reverse order - the first registered is the last to run - when the program terminates, either by calling the exit function or returning from main. The atexit callbacks typically implement "clean up" functions that close databases, remove temporary files, or otherwise leave the system in a stable, uncluttered state. Significantly, atexit is a library function, written before the client. Consequently, the client must adhere to its established signature when defining the callback functions.
The callback function
Calling the supplier
Existing library supplier
void func()
{
. . .
}
atexit(func);
int atexit( void (*f)() )
{
. . .
}
(a)
(b)
(c)
Function pointers: Client-side operations using callback functions.
atexit restricts the registered functions, requiring a void return type and disallowing any parameters, but does not restrict the code in the function bodies. Other supplier functions may have different requirements.
It's relatively easy for application or client programs to use atexit and similar library supplier functions. Applications are responsible for defining and registering the callback functions ((a) and (b)), but the atexit supplier hides the troublesome parameter definition (c).
Defining an appropriate callback function (ellipses denote extraneous detail omitted for simplicity).
Calling the atexit function and passing the address of the callback function.
The atexit library function define the function pointer parameter f. The definition consists of all the highlighted code.
#include <iostream>
#include <stdlib.h> // for the atexit prototype
using namespace std;
void test1()
{
cout << "Test 1\n";
}
void test2()
{
cout << "Test 2\n";
}
int main()
{
atexit(test1);
atexit(test2);
cout << "main is done\n";
return 0;
}
Example: atexit.
The example program demonstrates the syntax for using the atexit function. When executed, the program displays the following output on the console:
main is done
Test 2
Test 1
Pointers and Function Calls
callback, function pointer, function call operator, static, default arguments, module, compilation unit, class, global variable, scope, local scope, global scope, nullptr
The previous examples illustrate the general client-side callback syntax but not how to run a callback function. When using a library supplier function (e.g., atexit), programmers can ignore how the supplier saves and runs the callback. However, this detail matters when they need to create a customized supplier. The program must save asynchronous callback functions to run them later. The following examples illustrate different implementations with increasing levels of encapsulation. However, in each example the syntax for saving and running a callback function is the same.
C-style callbacks: Global and modular solutions.
With limited scope, C programs must use a global variable to store a callback function for later execution.
Defining and registering the callback function remains unchanged from the previous examples.
Prototypes for the functions registering and running the callback function.
The supplier, cb_param, stores the callback functions address in the global variable cb. The run runs the callback. The parentheses form the function-call operator, which treats its left-hand operand as the address of a function. The first version, (i), makes the variable cb fully global and accessible throughout the program. If the supplier code is in a separate file (making it a distinct compilation unit), adding the static keyword (ii) makes that file a module, restricting access to cb to the functions defined in the file.
Non-object-oriented C++ callback: A default argument.
A default argument allows a function, supplier in this example, to exhibit two distinct behaviors - in essence, it behaves like two functions.
A function prototype, typically placed in a header file, is necessary to specify a default value (highlighted in yellow).
The if-statement checks the parameter, determining the function's behavior. If the client passes the address of a callback function, supplier saves it in the local variable cb; if the parameter is null (i.e., it contains nullptr), supplier runs the saved function. Making cbstatic retains the saved value after supplier exits while retaining its local scope (see static Variables).
Calling supplier with a callback function argument causes the function to save the callback's address. Calling it without an argument causes it to run the saved callback.
class supplier
{
private:
void (*cb)(); // a member variable
public:
supplier(void (*cb_param)()) // a constructor function
{
cb = cb_param;
}
void run() // a member function
{
cb();
}
};
Object-oriented C++ callback: Managing scope with a class.
Although the textbook doesn't formally introduce classes for another three chapters, they provide the most robust way to implement generalized asynchronous callback functions. The supplier class makes the callback-function variable a member, limiting access to it. Only instances of the supplier class (i.e., objects instantiated from it) can access cb, and only through the member functions: the constructor and run. If this forward reference to classes and objects is unclear, please skip it and return later.
The supplier class with three members: a member variable and two member functions.
The client continues to define the callback function but creates and uses an object to manage it.