See the code below – I want to know how to, or if it is even possible to, write the body of A::DoThisOrThat()
class A
{
void DoThis( void ) { // any function body you like... }
void DoThat( void ) { // any function body you like... }
void DoThisOrThat( const bool doThis );
};
void A::DoThisOrThat( const bool doThis )
{
void (*pMemberFunction)( void );
pMemberFunction = doThis? &A::DoThis : &A::DoThat;
(*pMemberFunction)(); // member function invoked controlled by parameter
}
All three lines of this function may need rewriting to correctly scope the member function. As written, I get a calling convention conflict on the second line where I assign pMemberFunction. I cannot lay my hands on a simple example clarifying this – all the examples easily found declare a member variable to hold the member function pointer. Can I not just create a local variable to do the same?
I might be missing something, but isn’t it much easier and simpler to do this?
Assuming you really want to go the function pointer route, realize that pointer to member functions are completely different beasts from pointers to non-member functions. One of the ways they are different is that you need to provide an object for the function to invoke upon. The syntax is as follows:
Note that when declaring a pointer to member function, you have to also specify the class (note the
A::*) and the object (note thethis->*). Also remember that when forming pointers to members you have to fully qualify the function name, even within the class, and use the ampersand (e.g.&A::DoThis, which you’ve correctly done).