⚙️ C++ Intermediate

What are function pointers and std::function in C++?

Why Interviewers Ask This

This question targets practical, hands-on experience with C++. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

Function pointers store the address of a function and allow calling functions indirectly. Basic function pointer: int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } // Declare: return_type (*ptr_name)(param_types) = &function; int (*op)(int, int) = &add; std::cout << op(3, 4); // 7 op = subtract; // Reassign std::cout << op(3, 4); // -1 // Typedef for readability: typedef int (*BinaryOp)(int, int); BinaryOp operations[] = {add, subtract};. std::function (C++11): a type-erased wrapper that can hold any callable — function pointer, lambda, functor, member function: #include <functional> std::function<int(int, int)> op; // Holds int(int,int) callable op = add; // Regular function op = [](int a, int b) { return a * b; }; // Lambda struct Multiplier { int operator()(int a, int b) { return a * b; } }; op = Multiplier{}; // Functor std::cout << op(3, 4); // Works for all!. Storing in containers: std::map<std::string, std::function<double(double)>> mathFns; mathFns["sin"] = std::sin; mathFns["cos"] = std::cos; mathFns["square"] = [](double x) { return x * x; }; mathFns["sin"](3.14159); // Call by name. std::function overhead: std::function uses type erasure — heap allocation and virtual dispatch. For performance-critical code, use auto with lambdas or templates instead: template<typename F> void applyTo(std::vector<int>& v, F func) { for (auto& x : v) x = func(x); }. Binding member functions: std::function<void(int)> f = std::bind(&MyClass::method, &obj, std::placeholders::_1);.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last C++ project, I used this when...' immediately makes your answer more credible and memorable.