0

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
q126y
  • 1,589
  • 4
  • 18
  • 50
  • 1
    duplicate from [link](http://stackoverflow.com/questions/16778498/c-pointer-to-member-function) – Jerome Nov 19 '15 at 08:17
  • 1
    It is consistent with how pointers to data members work. The implicit conversion of a function name into a function pointer is like the implicit conversion of an array name to a pointer (to the first element). It is a feature inherited from C. Making the same sort of things work for pointers to members (whether functions or not) would mess up syntax that allows derived classes to access members of their base - and access of namespace members. – Peter Nov 19 '15 at 11:06

1 Answers1

2

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.

TartanLlama
  • 63,752
  • 13
  • 157
  • 193