I’ve been looking for the answer to this question but it seems quite difficult to get it, which brings me finally here.
It’s a syntax that we have to put the & right before pointer to member function.
For example here.
class Test;
typedef void (Test::*fpop)();
class Test
{
public:
void Op1(){}
};
int main(){
fpop pFunc;
pFunc = &Test::Op1; // we must need the &
return 0;
}
However, when I take a look at ON_COMMAND(or any other messages) in MFC, it seems a bit different from what I think is right.
VS6.0 is okay. It follows the right syntax as you see below.
You can clearly see & before memberFxn.
#define ON_COMMAND(id, memberFxn) \ // VS6.0
{ WM_COMMAND, CN_COMMAND, (WORD)id, (WORD)id, AfxSig_vv, (AFX_PMSG)&memberFxn },
// ON_COMMAND(id, OnFoo) is the same as
// ON_CONTROL(0, id, OnFoo) or ON_BN_CLICKED(0, id, OnFoo)
But in VS2008, it goes a bit weird. There is no & before memberFxn.
#define ON_COMMAND(id, memberFxn) \ // VS2008
{ WM_COMMAND, CN_COMMAND, (WORD)id, (WORD)id, AfxSigCmd_v, \
static_cast<AFX_PMSG> (memberFxn) },
// ON_COMMAND(id, OnBar) is the same as
// ON_CONTROL(0, id, OnBar) or ON_BN_CLICKED(0, id, OnBar)
Moreover, in spite of the fact that there is no & before memberFxn,
each line below works perfectly.
- ON_COMMAND(ID_APP_ABOUT, CSingleApp::OnAppAbout) // &
- ON_COMMAND(ID_APP_ABOUT, &CSingleApp::OnAppAbout) // no &
I tried to find why, and I was curious if it could be because of static_cast<> but it turned out that static_cast has nothing to do with it.
So I am wondering why in VS2008 I have 2 choices where I put the & or I don’t have to put the &.
The only correct way to form a pointer to member in C++ is with
&and the class qualifier (in this caseCSingleApp::).The Visual C++ compiler has always been more relaxed and has allowed things not normally permitted in the language such as leaving of the qualifier when forming the pointer from inside the class’ context and not needing to use
&when it is strictly required.