C++ Function pointers

Started by
4 comments, last by Zahlman 16 years, 9 months ago
Is there a way to have a function pointer to a method of another class for a patricular instance of that class. something like this This gives me a error "'&' : illegal operation on bound member function expression" any ideas on how i can do this?

class A
{
public:
	void (*fptr)();
	A(){}
	~A(){}
};
class B
{
public:
	B(){}
	~B(){}
	void test(A* a_ptr)
	{
		
		a_ptr->fptr=&print
	}
	void print(){cout<<"Testing";}

};
Advertisement
print is a member function.

You need to use a member function pointer variable to store a pointer to a member function.
ok so when i do this shouldnt this print testing.
it actually doesnt do anything.


class A{public:	void (B::*fptr)();	A(){}	~A(){}};class B{public:	B(){}	~B(){}	void test(A* a_ptr)	{				a_ptr->fptr=&B::print;	}	void print(){cout<<"Testing";}};int main(){	A* a= new A();	B b;	b.test(a);	a->fptr;	return 0;}
a->fptr is a pointer-to-member-function. Writing a->fptr; is
the same as writing &B::print, it just evaluates to the address of a member function, discards that address, and then moves on to the next instruction.

If you wish to call a member function through a pointer-to-member-function, you must use the syntax:

(instance.*ptr)();

Where instance is an instance of type T and ptr is a pointer to a member function of that same type T. In your case, the code would be:

(b.*(a->fptr))();
yes thankyou. I knew it was something like that but i just wasnt sure, i had never used function pointers before.
Thank you.
Gamedev once again pulls through :)
Pointers to member functions.

But you really, *really* shouldn't need to be doing this except in very, *very* strange circumstances. What are you trying to accomplish?

This topic is closed to new replies.

Advertisement