Pointer to Function in C++
A variable that holds a function's address. Callbacks and qsort live here.
Function pointers are one of the most powerful features in C++ that allow you to store and call functions dynamically. They enable advanced programming techniques like callbacks, function tables, event handling, and implementing design patterns. Understanding function pointers is essential for writing flexible, reusable, and efficient C++ code.
1#include <iostream>2#include <vector>3#include <algorithm>4#include <string>5using namespace std;67// Basic arithmetic functions8int add(int a, int b) {9 return a + b;10}1112int subtract(int a, int b) {13 return a - b;14}1516int multiply(int a, int b) {17 return a * b;18}1920int divide(int a, int b) {21 if (b != 0) {22 return a / b;23 }24 return 0;25}2627// Function with different signature28void greet(string name) {29 cout << "Hello, " << name << "!" << endl;30}3132// Function that takes function pointer as parameter (callback)33void performOperation(int a, int b, int (*op)(int, int), string opName) {34 cout << a << " " << opName << " " << b << " = " << op(a, b) << endl;35}3637// Function that returns a function pointer38int (*getOperation(char op))(int, int) {39 switch(op) {40 case '+': return add;41 case '-': return subtract;42 case '*': return multiply;43 case '/': return divide;44 default: return nullptr;45 }46}4748int main() {49 cout << "=== BASIC FUNCTION POINTER USAGE ===" << endl;5051 // Declare function pointer: returnType (*pointerName)(parameters)52 int (*operation)(int, int);5354 int num1 = 20, num2 = 5;5556 // Point to add function57 operation = add;58 cout << num1 << " + " << num2 << " = " << operation(num1, num2) << endl;5960 // Point to subtract function61 operation = subtract;62 cout << num1 << " - " << num2 << " = " << operation(num1, num2) << endl;6364 // Point to multiply function65 operation = multiply;66 cout << num1 << " * " << num2 << " = " << operation(num1, num2) << endl;6768 // Point to divide function69 operation = divide;70 cout << num1 << " / " << num2 << " = " << operation(num1, num2) << endl;7172 cout << "73=== ARRAY OF FUNCTION POINTERS ===" << endl;74 // Array of function pointers75 int (*operations[])(int, int) = {add, subtract, multiply, divide};76 char opSymbols[] = {'+', '-', '*', '/'};7778 for (int i = 0; i < 4; i++) {79 cout << num1 << " " << opSymbols[i] << " " << num280 << " = " << operations[i](num1, num2) << endl;81 }8283 cout << "84=== USING TYPEDEF FOR READABILITY ===" << endl;85 // Using typedef to make function pointer syntax cleaner86 typedef int (*MathOp)(int, int);87 MathOp op1 = add;88 MathOp op2 = multiply;89 cout << "Using typedef: " << op1(10, 5) << " and " << op2(10, 5) << endl;9091 cout << "92=== CALLBACK FUNCTION EXAMPLE ===" << endl;93 // Passing function pointer as parameter (callback)94 performOperation(15, 3, add, "+");95 performOperation(15, 3, subtract, "-");96 performOperation(15, 3, multiply, "*");97 performOperation(15, 3, divide, "/");9899 cout << "100=== FUNCTION POINTER FROM FUNCTION ===" << endl;101 // Getting function pointer from another function102 int (*selectedOp)(int, int) = getOperation('+');103 if (selectedOp != nullptr) {104 cout << "Result from getOperation('+'): " << selectedOp(8, 4) << endl;105 }106107 cout << "108=== FUNCTION POINTER WITH STL ===" << endl;109 // Using function pointer with STL algorithms110 vector<int> numbers = {5, 2, 8, 1, 9, 3};111 cout << "Original: ";112 for (int n : numbers) cout << n << " ";113114 // Sort using function pointer115 bool (*compare)(int, int) = [](int a, int b) { return a > b; };116 sort(numbers.begin(), numbers.end(), compare);117118 cout << "119Sorted (descending): ";120 for (int n : numbers) cout << n << " ";121 cout << endl;122123 cout << "124=== NULL POINTER CHECK ===" << endl;125 // Checking for null function pointer126 int (*nullOp)(int, int) = nullptr;127 if (nullOp == nullptr) {128 cout << "Function pointer is null (safe to check)" << endl;129 }130131 return 0;132}
Output
=== BASIC FUNCTION POINTER USAGE ===
20 + 5 = 25
20 - 5 = 15
20 * 5 = 100
20 / 5 = 4
=== ARRAY OF FUNCTION POINTERS ===
20 + 5 = 25
20 - 5 = 15
20 * 5 = 100
20 / 5 = 4
=== USING TYPEDEF FOR READABILITY ===
Using typedef: 15 and 50
=== CALLBACK FUNCTION EXAMPLE ===
15 + 3 = 18
15 - 3 = 12
15 * 3 = 45
15 / 3 = 5
=== FUNCTION POINTER FROM FUNCTION ===
Result from getOperation('+'): 12
=== FUNCTION POINTER WITH STL ===
Original: 5 2 8 1 9 3
Sorted (descending): 9 8 5 3 2 1
=== NULL POINTER CHECK ===
Function pointer is null (safe to check)In this one
- What function pointers are and how they work
- How to declare and use function pointers
- How to create arrays of function pointers
- How to use function pointers as callbacks
- How to implement function tables and jump tables
- How to use typedef to simplify function pointer syntax
- How function pointers compare to lambdas and functors
- Real-world applications of function pointers
- Best practices and common mistakes to avoid
- Performance considerations with function pointers
When to use this
Use function pointers when: implementing callback mechanisms, creating function tables for dynamic selection, implementing design patterns like Strategy, handling events in event-driven programming, building plugin systems, creating state machines, working with legacy C code, implementing sorting with custom comparators, and when you need runtime function selection.
How it works
- 1
Understand that functions have memory addresses just like variables
- 2
Learn the syntax: returnType (*pointerName)(parameters)
- 3
Declare a function pointer matching your function signature
- 4
Assign a function address to the pointer (function name or &function)
- 5
Call the function through the pointer using (*pointer)(args) or pointer(args)
- 6
Create arrays of function pointers for function tables
- 7
Use typedef to make function pointer types more readable
- 8
Pass function pointers as parameters for callbacks
- 9
Return function pointers from functions for dynamic selection
- 10
Always check for null before calling through function pointers
Methods
01Basic Function Pointer
What it does. The fundamental way to store and call functions dynamically using pointers.
When to use. Use when you need to select and call different functions at runtime based on conditions or user input. Perfect for implementing calculators, menu systems, or any scenario where function selection is dynamic.
How it works. A function pointer stores the memory address of a function. When you call through the pointer, the program jumps to that memory address and executes the function code. The pointer can be reassigned to point to different functions with matching signatures.
Trade-offs. Pros: Dynamic function selection, flexible code design, enables callbacks. Cons: Cannot be inlined by compiler, slight performance overhead, syntax can be complex.
1int (*op)(int, int) = add; int result = op(5, 3);
02Array of Function Pointers
What it does. Creating a lookup table of functions for efficient function selection based on index.
When to use. Use when you have multiple related functions and want to select them based on an index or enum value. Ideal for implementing state machines, command processors, or operation dispatchers.
How it works. An array stores multiple function addresses. You can index into the array to select a function, then call it. This provides O(1) function selection and is more efficient than if-else chains or switch statements for many functions.
Trade-offs. Pros: Fast selection (O(1)), clean code, easy to extend. Cons: All functions must have same signature, requires careful index management.
1int (*ops[])(int, int) = {add, subtract, multiply}; int result = ops[0](10, 5);
03Callback Functions
What it does. Passing function pointers as parameters to enable functions to call back to user-provided code.
When to use. Use when you want to allow users of your function to customize behavior. Common in event handling, sorting algorithms, and library APIs where behavior needs to be customizable.
How it works. A function receives a function pointer as a parameter. During execution, it calls this pointer to invoke the user-provided function. This enables flexible, reusable code where behavior can be customized without modifying the original function.
Trade-offs. Pros: Highly flexible, enables customization, promotes code reuse. Cons: Can make code flow harder to follow, requires careful documentation.
1void process(int data, void (*callback)(int)) { callback(data); }
Edge cases
Null Function Pointer
What happens when you call a null function pointer?
1int (*op)(int, int) = nullptr;2int result = op(5, 3); // CRASH!
Calling a null function pointer causes undefined behavior and typically crashes the program. Always check for null before calling: if (op != nullptr) { result = op(5, 3); }
Signature Mismatch
What happens if function pointer signature doesn't match the function?
1int add(int a, int b);2void (*op)(int) = add; // Error: signature mismatch
The compiler will give an error if signatures don't match exactly. Both return type and all parameters must match. This is a compile-time check that prevents runtime errors.
Function Pointer to Member Function
Can you use function pointers with class member functions?
1class MyClass {2public:3 void memberFunc() { }4};5// Regular function pointer won't work6void (*ptr)() = &MyClass::memberFunc; // Error
Regular function pointers cannot point to member functions. You need member function pointers with different syntax: void (MyClass::*ptr)() = &MyClass::memberFunc;
What's going on
Function pointers are one of the most powerful and flexible features in C++ programming. They allow you to store the address of a function and call it dynamically, enabling advanced programming techniques that make your code more flexible, reusable, and efficient.
##
What is a Function Pointer?
A function pointer is a variable that stores the memory address of a function. Just like a regular pointer stores the address of a variable, a function pointer stores the address of a function, allowing you to call that function indirectly.
Key Concept:
Functions, like variables, have memory addresses. A function pointer lets you store and use these addresses to call functions dynamically.
##
Basic Syntax
The syntax for declaring a function pointer is:
1
1returnType (*pointerName)(parameterTypes);
Important Notes:
*pointerName are crucialExample:
1int (*operation)(int, int);234// Assign function address5operation = add;678// Call function through pointer9int result = operation(5, 3); // Calls add(5, 3)
##
1// Function pointer for: int function(int, int)
How Function Pointers Work
1.
Function Address:
Every function has a memory address where its code is stored
2.
Pointer Storage:
A function pointer stores this address
3.
Indirect Call:
When you call through the pointer, the program jumps to that address and executes the function
4.
Dynamic Selection:
You can change which function the pointer points to at runtime
Memory Representation:
1Function: add() Function: subtract()2Address: 0x1000 Address: 0x20003| |4| |5v v6[operation pointer] → Can point to either
##
Common Use Cases
###
Callback Functions
Function pointers are commonly used for callbacks - functions that are called by other functions to perform specific tasks.
Example:
1void processData(int data, void (*callback)(int)) {2int result = data * 2;34// Call the callback function5callback(result);6}78void printResult(int value) {910cout << "Result: " << value << endl;11}121314// Usage15processData(10, printResult); // Calls printResult with result
1// Process data
Questions people ask
What is a function pointer?
A function pointer is a variable that stores the memory address of a function. It allows you to call functions indirectly and select which function to call at runtime, enabling dynamic behavior and flexible code design.
Why are parentheses important in function pointer syntax?
Parentheses are crucial because `int *operation(int, int)` declares a function that returns a pointer, while `int (*operation)(int, int)` declares a pointer to a function. The parentheses change the meaning completely.
What is the difference between function pointer and function call?
A function pointer stores the address of a function (no parentheses), while a function call executes the function (with parentheses and arguments). Example: `operation = add;` (pointer) vs `add(5, 3);` (call).
Can function pointers point to any function?
Function pointers can only point to functions with matching signatures (same return type and parameter types). The signature must match exactly, though const and reference qualifiers can sometimes be compatible.
What are function pointers used for?
Function pointers are used for: callback functions, function tables/jump tables, implementing design patterns (Strategy, Observer), event handling, plugin systems, state machines, and dynamic function selection.
Are function pointers faster than regular function calls?
Function pointers are slightly slower than direct function calls because they require an indirect jump. However, the difference is usually negligible. Direct calls can be inlined by the compiler, but function pointer calls typically cannot.
Can I use function pointers with lambdas?
Yes, but only if the lambda doesn't capture anything (stateless lambda). Stateless lambdas can be converted to function pointers. Lambdas with captures cannot be converted to function pointers.
What is the difference between function pointers and std::function?
Function pointers are lightweight and type-specific. std::function is more flexible, can store any callable (functions, lambdas, functors), but has more overhead. Use function pointers for simple cases, std::function for flexibility.