devxlogo

Use Functor for Callbacks in C++

Using the callback function in C is pretty straightforward, but in C++ it becomes little tricky.

If you want to use a member function as a callback function, then the member function needs to be associated with an object of the class before it can be called. In this case, you can use functor.

Suppose you need to use the member function get() of the class base as a callback function

class base{public:	int get ()	{ return 7;}};

Then, you need to define a functor:

class CallbackFunctor{	functor(const base& b):m_base(b)	{}	int operator() ()	{		return m_base.get();	}};

Now you can use an object of CallbackFunctor as a callback function as follows.

Define the function that needs a callback to take an argument of type CallbackFunctor:

void call (CallbackFunctor& f){	cout << f() << endl;}int main (){	base b;	functor f(b);	call(f);}

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Seasoned Architects Evaluate New Tech

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.