devxlogo

Prefer Function Objects to Function Pointers

Prefer Function Objects to Function Pointers

Passing a function pointer is a common practice in event-driven systems, whereby a callback routine is invoked through a pointer. C++, however, offers a better alternative to function pointers: function objects. Using a function object instead of a pointer offers several advantages. First, your code is more resilient to changes, since the object containing the function can be modified without affecting its users. In addition, compilers can inline a function object, thereby enhancing performance even further. But perhaps the most compelling argument in favor of function objects is their genericity. A function object can embody a generic algorithm by means of a member template, something not easily accomplished with ordinary function pointers. In the following example, a function object implements a generic negation operator:

 #include  #include using namespace std;class negate {  public : template < class T > T operator()  (T t) const { return -t;} //generic negation operator };void callback(int n, const negate& neg) { //pass a function object rather than a function pointer  n = neg(n);  // invoke the overloaded () operator to negate n  cout << n;}void main() { callback(5, negate() ); //output -5}
See also  lenso.ai - an AI reverse image search platform
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist