Pointers to class member functions

Started by
3 comments, last by snk_kid 19 years, 8 months ago
Hi! I use MSVC++ 6.0. I am wondering how can I get a pointer to a function that is a class member. Does the member function needs to be defined as 'static' ?? Thanks! :)
___Quote:Know where basis goes, know where rest goes.
Advertisement
link [grin]
Thanks, TomasH. Unfortunately, I didn't find my answer there.

I'll try to be more precise. Take a look at the following code :
// *** somwhere in GameEngine class *** //// Pointer to the main program routineint (*fMainRoutine) (float dt);	// Sets a game main routine pointer	void SetMainRoutine (int (*f) (float) = NULL) { fMainRoutine = f; };// *** inside IntroModule class *** //int	HandleMain(float dt) { return 1; } // *** somewhere in a code *** //GameEngine.SetMainRoutine (IntroModule::Instance().HandleMain);


The error I get is :
error C2664: 'SetMainRoutine' : cannot convert parameter 1 from 'int (float)' to 'int (__cdecl *)(float)'
None of the functions with this name in scope match the target type

Forgive me my stupid questions but I don't know how to solve the problem myself. What can I do ??

Thanks :)

-----------------
___Quote:Know where basis goes, know where rest goes.
class foo {public:  void bar() { printf ( "foo::bar\n" ); }  void baz() { printf ( "foo::baz\n" ); }};int main() {  // declare memFuncPointer to of type 'pointer to void function  // member of foo class'.  void(foo::*memFuncPointer)(void);  foo f;  // assign memFuncPointer to the bar member function  memFuncPointer = foo::bar;  // call memFuncPointer (bar) on f  (f.*memFuncPointer)();  // assign memFuncPointer to the baz member function  memFuncPointer = foo::baz;  // call memFuncPointer (baz) on f  (f.*memFuncPointer)();  return 0;}


As you can see, the syntax of pointers to member-functions is significantly uglier than pointers to free functions.

The alternative is, as you suggested, to make the member function static, in which case you can use the same syntax as would for free functions.

- Neophyte

P.S. The link provided by TomasH contained all the information you were looking for if you had bothered to actually read the page.
Hi you cannot assign a member function to a normal pointer to function and you can't assign it that way besides, this is how it works like so:

#include <iostream>struct a {  void do_func() const { std::cout << "doing it\n"; }};typedef void (a::*PMF)(void) const;int main() {   a i;   PMF f = &a::do_func;   //direct call   i.do_func();   //indirect call   (i.*f)();   return 0;}


You can't use a pointer to member function with-out some instance of the type.

This topic is closed to new replies.

Advertisement