Function Pointers

Storing Function Pointers

How can I store multiple function pointers of the same type in a collection like a vector or array?

Abstract art representing computer programming

To store multiple function pointers of the same type in a collection, you can use the same type alias approach we showed in the lesson. For example:

#include <iostream>
#include <vector>

using IntPredicate = bool (*)(int);

bool isEven(int n) { return n % 2 == 0; }

bool isPositive(int n) { return n > 0; }

int main() {
  std::vector<IntPredicate> Predicates{
    isEven, isPositive};

  for (auto& Pred : Predicates) {
    std::cout << std::boolalpha;
    std::cout << Pred(4) << '\n';   
    std::cout << Pred(-1) << '\n';  
  }
}
true
false
false
false

Here, we define an IntPredicate type alias for a function pointer that takes an int and returns a bool. We can then use this alias to specify the type stored in our vector.

We populate the vector with our isEven and isPositive function pointers. Later, we can iterate over the vector and call each function pointer with the () operator, just like we would with a normal function.

This same approach works for arrays and other collections that can store the function pointer type.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved