Jump to content
  • Advertisement
Sign in to follow this  
Ksingh30

C++ Function pointers

This topic is 4119 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
print is a member function.

You need to use a member function pointer variable to store a pointer to a member function.

Share this post


Link to post
Share on other sites
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
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
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!