Function pointers to member functions
Posted
by Jacob
on Stack Overflow
See other posts from Stack Overflow
or by Jacob
Published on 2010-04-30T16:00:29Z
Indexed on
2010/04/30
16:07 UTC
Read the original article
Hit count: 231
There are several duplicates of this but nobody explains why I can use a member variable to store the pointer (in FOO
) but when I try it with a local variable (in the commented portion of BAR
), it's illegal. Could anybody explain this?
#include <iostream>
using namespace std;
class FOO
{
public:
int (FOO::*fptr)(int a, int b);
int add_stuff(int a, int b)
{
return a+b;
}
void call_adder(int a, int b)
{
fptr = &FOO::add_stuff;
cout<<(this->*fptr)(a,b)<<endl;
}
};
class BAR
{
public:
int add_stuff(int a, int b)
{
return a+b;
}
void call_adder(int a, int b)
{
//int (BAR::*fptr)(int a, int b);
//fptr = &BAR::add_stuff;
//cout<<(*fptr)(a,b)<<endl;
}
};
int main()
{
FOO test;
test.call_adder(10,20);
return 0;
}
© Stack Overflow or respective owner