Code
class cat{
public:
void walk(){
printf("cat is walking \n");
}
void myAbc(){
void (*pKoo)();
pKoo = &this->walk;
}
void myDef(){
void(cat::*pFoo)();
pFoo = &this->walk;
}
}
};
Result
- void (*pKoo)(); – No problem
- pKoo = &this->walk; – Compiling error
- void(cat::*pFoo)(); – No problem
- pFoo = &this->walk; – compile error;
Question
- Why no 2 impossible? If Impossible, Then what is the use of No 1?
- Why no 4 impossible? If Impossible, Then what is the use of No 3?
Please help for conceptual explanation. thank you
My compiler gives an error message:
meaning that you can’t convert a pointer-to-member-function to a pointer-to-function. They are incompatible types; a pointer-to-function can be called directly, while a pointer-to-member-function needs to be applied to an object. So the type you assign to has to be pointer-to-member-function, or
void (cat::*)();, as you correctly use in 3.It’s used to store a pointer to a static or non-member function.
(I assume you mean 4, not 3.) My compiler gives an error message:
For some reason, you’re not allowed to take the address of a member function using an object (or pointer); you have to use the class name instead. We can only speculate on why this isn’t allowed; perhaps because it’s not entirely clear which override should be chosen if it’s virtual, or perhaps for some other reason.
Whatever the reason, use the allowed syntax:
pFoo = &cat::walk;