Function Pointers

Pointers to functions

Interview Relevant: Advanced concept

Function Pointers

Function pointers store addresses of functions for callbacks and dynamic dispatch.

Code Examples

Function pointers for callbacks and dynamic dispatch.

cpp
1int add(int a, int b) { return a + b; }
2int subtract(int a, int b) { return a - b; }
3
4// Function pointer declaration
5int (*operation)(int, int);
6
7// Assign and call
8operation = add;
9cout << operation(5, 3);  // 8
10
11operation = subtract;
12cout << operation(5, 3);  // 2
13
14// Function pointer as parameter
15void calculate(int a, int b, int (*op)(int, int)) {
16    cout << op(a, b) << endl;
17}
18calculate(10, 5, add);       // 15
19calculate(10, 5, subtract);  // 5
20
21// Array of function pointers
22int (*ops[])(int, int) = {add, subtract};
23cout << ops[0](3, 2);  // 5

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In