Creating a Callback Function Pointer

Creating a Callback Function Pointer

I am using Microsoft Visual C++ 6.0 and am trying to create a callback function pointer to the public member of a class, but I keep getting the following error:

 error C2664: 'callback' : cannot convert parameter 1 from 'void' to 'void (__cdecl *)(void)'

Here is the code I am trying:

#include class bb  {public:	void callback(void (*f)());	void callback2();	bb();	virtual ~bb();};bb::bb(){}bb::~bb(){}void bb::callback(void (*f)()){	f();}void bb::callback2(){	cout << "callback2 called." << endl;}int main(int argc, char* argv[]){	bb *tmp = new bb;	tmp->callback(tmp->callback2());	return 0;}

TIA for any help.

For starters, by appending the () to the end of callback2 in the following line:


you are telling the compiler to call this function and then send the return value (in this case void) as an argument to tmp->callback. That definitely won’t work.

Unfortunately, removing the parentheses won’t make this work either. When C++ code calls a method on an object, is passes a hidden argument that is the pointer to the object (this). The downside to this is that you can’t treat class member functions and pointers to them the same way you’d handle regular functions.

Some things to try include making your member function static and checking out the .* and –>* (pointer to member) operators.

See also  How College Students Can Shape the Future of Tech Responsibility

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