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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With