Why can't a pointer to a non-constant member function indicate a member function and vice versa?

What is the reason why member function pointers cannot point to member functions?

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

Later in code:

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

This code creates:

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

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

In the opposite situation:

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

Mistake:

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

The second case is pretty clear. const pointer should not modify an object, so it cannot hold a function that does this. But why is it impossible to assign a const member function to a non-const member function as in the first case?

It looks usually for ordinary pointers, where dropping the const to non-const would make it possible to change the value, but I don’t see the point here where const-correctness is checked in the function definition, before that purpose.

+8
c ++ pointers const function-pointers
source share
2 answers

Non-static member functions have an additional hidden parameter, this . Given this extra hidden parameter, the non-static void A::f() const; behaves the same as void A__f(const A *__this) , and the behavior you see for member functions models the behavior for functions that are not members.

 void f(void *); void (*pf)(const void *) = f; // also an error 

As for whether it can break down on any implementation, I believe that theoretically, implementations are allowed to read the void * parameter from a different register than the const void * parameter, and if so, then the result of the conversion (whether they were valid) is not could be used to call f correctly. I have no idea why any developer made such a decision, and I do not know any real implementation that does this, but it is allowed by the standard.

+3
source share

What is the reason why member function pointers cannot point to member functions?

Because the const modifier is part of the function signature. When you declare a pointer to a function, this function pointer can only be used to assign function pointers that have the same function signature.

+4
source share

All Articles