Sign in to follow this  
Ksingh30

C++ Function pointers

Recommended Posts

Ksingh30    100
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";}

};

Share this post


Link to post
Share on other sites
Ksingh30    100
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;
}

Share this post


Link to post
Share on other sites
ToohrVyk    1595
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))();

Share this post


Link to post
Share on other sites
Ksingh30    100
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 :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this