Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Aug 12, 1999

Creating a Callback Function Pointer

Question:
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.

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

 
tmp->callback(tmp->callback2());
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.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap