Reputation: 1671
The following code runs fine
#include <iostream>
using namespace std;
void fun()
{
cout<<"having some fun";
}
typedef void (*funptr)();
int main() {
// your code goes here
funptr p=fun;
p();
return 0;
}
This one doesn't work.
#include <iostream>
using namespace std;
class myclass
{
public:
void fun()
{
cout<<endl<<"having fun inside myclass"<<endl;
}
};
typedef void (myclass::*funptr)();
int main() {
// your code goes here
funptr p=myclass::fun; //THIS DOESN'T WORK. WHY?
myclass m;
(m.*p)();
return 0;
}
Why is & operator needed for member functions?
Upvotes: 0
Views: 101
Reputation: 65730
Lvalues of function type T
can be converted to T*
implicitly ([conv.func]/4.3
), but there is no analogous rule for member functions.
I'm not sure what the reasoning behind this is, so I guess my answer is "the standard says so". Perhaps it's because member function pointers are not used too often, so mandating extra implementation details for them was seen as unnecessary.
Upvotes: 2