Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pointer to non-const member function can't point const member function and opposite?

Tags:

What is the reason why pointers to member functions, can't point to const member functions?

struct A {
    void g() {};
    void f() const {}
};

Later in code:

void (A::* fun)() = &A::f;

This code produces:

error: cannot convert ‘void (A::*)()const’ to ‘void (A::*)()’ in initialization

Of course it compiles with &A::g instead of &A::f.

In opposite situation:

void (A::* fun)() const = &A::g;

The error is:

error: cannot convert ‘void (A::*)()’ to ‘void (A::*)()const’ in initialization

The second case is rather clear. const pointer isn't expected to modify the object so it can't hold the function which does it. But why it's not possible to assign const member function to non-const member function as in the first case?

It looks like the rule for normal pointers where casting const to non-const would allow to modify the value, but I don't see the point here, where const-correctness is checked in function definition, before such assignment.