Main > Software Forum
Help requested: C++ member function pointers
Buddabing:
Hello,
The following code gives me a compiler error: "Cannot convert int(ExampleClass::*)() to int(*)() in assignment:
--- Code: ---#include <stdio.h>
class ExampleClass
{
public:
int (*member)(void);
int foo(void)
{
return 1;
}
int bar(void)
{
return 2;
}
void SetFoo(void)
{
member=&ExampleClass::foo; // <----------------error here
}
void SetBar(void)
{
member=&ExampleClass::bar; // <----------------error here
}
int CallMember(void)
{
return (*member)();
}
}
main(int argc, char **argv)
{
ExampleClass ex;
int result;
ex.SetFoo();
printf("result from SetFoo=%d\n",ex.CallMember());
ex.SetBar();
printf("result from SetBar=%d\n",ex.CallMember());
return 0;
}
--- End code ---
Any help correcting the syntax would be appreciated.
TIA,
Buddabing
Spartan:
Make foo and bar static, and pass in the instance of 'ex' as an argument.
youki:
class ExampleClass
{
public:
int (*member)(void);
static int foo(void)
{
return 1;
}
static int bar(void)
{
return 2;
}
void SetFoo(void)
{
member=&ExampleClass::foo;
}
void SetBar(void)
{
member=(&ExampleClass::bar);
}
int CallMember(void)
{
return (*member)();
}
};
It compiles under VC++
MustardTent:
The reason "static" needed is because member function pointers cannot be dereferenced without an associated object. For each member function a "this" pointer is passed implicitly, even though it is not in the function prototype.
Check out this for a little more info.
Buddabing:
That worked, but I need to be able to access other members of the class from within the static function:
--- Code: ---#include <stdio.h>
class ExampleClass
{
public:
int (*member_fn)(void);
int member_int;
static int foo(void);
static int bar(void);
void SetFoo(void);
void SetBar(void);
int CallMember(void);
};
int ExampleClass::foo(void)
{
member_int=1; //<---------------error
return 1;
}
int ExampleClass::bar(void)
{
member_int=2; //<---------------error
return 2;
}
void ExampleClass::SetFoo(void)
{
member_fn=&ExampleClass::foo;
}
void ExampleClass::SetBar(void)
{
member_fn=&ExampleClass::bar;
}
int ExampleClass::CallMember(void)
{
return (*member_fn)();
}
main(int argc, char **argv)
{
ExampleClass ex;
int result;
ex.SetFoo();
printf("result from SetFoo=%d, member_int=%d\n",
ex.CallMember(),ex.member_int);
ex.SetBar();
printf("result from SetBar=%d, member_int=%d\n",
ex.CallMember(),ex.member_int);
return 0;
}
--- End code ---
The error when this is compiled is "Invalid use of member 'ExampleClass::member_int' in static member function".
Navigation
[0] Message Index
[#] Next page
Go to full version