Passing Functions to Other Functions in C++

hands

Passing functions to other functions is a powerful tool that allows you to create flexible and modular code. In C++, you can do this in several ways: using function pointers, function objects, and lambda functions.

Function pointers

A function pointer stores the address of a function and allows you to call it through that pointer. Example:

include

void hello() {
std::cout << “Hello, world!” << std::endl;
}

void execute(void (*func)()) {
func();
}

int main() {
execute(hello);
return 0;
}

Here execute takes a pointer to a function and calls it.

Using Functors

A functor is a class with an overloaded operator() operator that allows you to use objects of this class as functions.

include

class Functor {
public:
void operator()() const {
std::cout << “Hello from functor!” << std::endl;
}
};

void execute(const Functor& func) {
func();
}

int main() {
Functor f;
execute(f);
return 0;
}

Functors are convenient when you need to store state between calls.

Lambda functions

Lambda functions are anonymous functions that can be passed to other functions.

include

void execute(const std::function &func) {
func();
}

int main() {
execute([]() { std::cout << “Hello from lambda!” << std::endl; });
return 0;
}

Lambda functions are especially handy when combined with standard STL algorithms.

Conclusion

Passing functions to other functions makes code more flexible and convenient. Function pointers are simple, functionors allow you to store state, and lambda functions provide brevity and ease of writing.