nikomaster nikomaster - 1 month ago 5
C++ Question

Call class method non-static initialised by pointer

I'm trying call a method initialised by pointer to a method of other class, i've followed this:
but it has not worked for me.

consider this:

class y
{
public:
int GetValue(int z)
{
return 4 * z;
}
};


class hooky
{
public:
int(hooky::*HookGetValue)(int);
};


int(hooky::*HookGetValue)(int) = (int(hooky::*)(int))0x0; // memory address or &y::GetValue;



int main()
{
hooky h; // instance
cout << h.*HookGetValue(4) << endl; // error
return 0;
}


the error that produces is:


[Error] must use '.' or '->' to call pointer-to-member function in
'HookGetValue (...)', e.g. '(... ->* HookGetValue) (...)'

Answer

The correct syntax to invoke a member function pointer is

(h.*HookGetValue)(4)

Update: the reason original code does not work as expected is because of operator precedence of C++: function invocation () is having higher precedence than ptr to member .*. Which means

h.*HookGetValue(4)

will be see as

h.*(HookGetValue(4))
Comments