There is a class that contains the doX method and a pointer to the pDoX function.

class X { public: void (*pDoX)(); void doX(); X() { pDoX = doX; } }; 

If you compile the code, an error is displayed:

xc: In constructor 'X::X()':
xc:9: error: argument of type 'void (X::)()' does not match 'void (*)()'

How to carry out the assignment correctly?

    1 answer 1

    The compiler must know to which object the message should be sent when accessing the function hidden behind the pointer, therefore the type of the variable must be appropriate

     class X { public: void (X::*pDoX)(); void doX(); X() { pDoX = &X::doX; } }; 

    Only it is necessary to cause, specifying specific object:

     int main() { X x; (x.*(x.pDoX))(); return 0; } 

    or so:

     int main() { X *px = new X(); (px->*(px->pDoX))(); return 0; } 
    • and in what kind of tasks it is required. do not tell me? - rojaster
    • <pre> void (* do_smth) (void); void Win9x_do_smth (void); void Win2k_do_smth (void); void WinXP_do_smth (void); // somewhere in the code ver = CheckForWindowsVersion (); if (ver = Win9x) do_smth = Win9x_do_smth; else if (ver = Win2k) do_smth = Win2k_do_smth; else if (ver = WinXP) do_smth = WinXP_do_smth; // somewhere further in the code do_smth (); // for XP is called after the fact void WinXP_do_smth (void) </ pre> - gecube
    • You can use an array of function pointers and select the desired one. One has only to make a fantasy. More function pointers are needed when working with dynamic libraries. So you can implement a system of plug-ins. In the above example, the pointer is needed to select a specific function from the set that will be called when the program runs under a specific OS. - gecube