C++ Function Pointers

Introduce 4 ways to define function pointers in C++.

  1. Traditional
  2. typedef
  3. using
  4. std::function

1. Traditional

Syntax

1
2
3
4
return_type (*pointer_name)(parameter_types1, parameter_types2);

// example
int (*funcPtr)(int, int);

2. typedef

Syntax

1
2
3
4
typedef return_type (*pointer_name)(parameter_types1, parameter_types2);

// example
typedef int (*funcPtr)(int, int);

funcPtr becomes an alias for the type “pointer to a function that takes two int parameters and returns an int”.

3. using

Syntax

1
2
3
4
using pointer_name = return_type (*)(parameter_types1, parameter_types2);

// example
using funcPtr = int (*)(int, int)

funcPtr becomes an alias for the type “pointer to a function that takes two int parameters and returns an int”.

4. std::function

Syntax

1
2
3
4
std::function<return_type(parameter_types1, parameter_types2)> pointer_name;

// example
std::function<int(int, int)> funcPtr;

5. Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <functional>

int add(int a, int b) {
return a + b;
}

int main() {
// 1. traditional
int (*funcPtr1)(int, int);
funcPtr1 = add;
std::cout << funcPtr1(1, 2) << '\n';

// 2. typedef
typedef int (*AddFunc_typedef)(int, int);
AddFunc_typedef funcPtr2 = add;
std::cout << funcPtr2(1, 2) << '\n';

// 3. using
using AddFunc_using = int (*)(int, int);
AddFunc_using funcPtr3 = add;
std::cout << funcPtr3(1, 2) << '\n';

// 4. std::function
std::function<int(int, int)> funcPtr4 = add;
std::cout << funcPtr4(1, 2) << '\n';

return 0;
}
Author

Joe Chu

Posted on

2024-09-10

Updated on

2024-09-10

Licensed under

Comments