CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Dec 2011
    Posts
    2

    Member function pointer to a member function

    Trying to create a class that has a member function pointer that points to a member function.
    Here is a basic example of what I'm trying to do:

    class X
    {
    public:
    X();
    short myFunction(void*, DWORD, byte);

    short (&X::fptr)(void*, DWORD, byte);
    };

    X::X()
    {
    fptr = &X::myFunction;
    }

    in the main program
    X myx;
    char *a;
    DWORD b;
    byte c;

    myx.*fptr(a, b, c); -> on compile I get 'fptr': identifier not found

    I have tried using typedef in various ways and have had no success. Any help would be awesome!

  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Member function pointer to a member function

    Quote Originally Posted by joshuawoodz View Post
    Trying to create a class that has a member function pointer that points to a member function.
    Here is a basic example of what I'm trying to do:
    Usage of typedef makes this a lot simpler:
    Code:
    class X
    {
        public:
        typedef short (X::*ptrFn)(void*, DWORD, byte);
        X();
        short myFunction(void*, DWORD, byte);
        ptrFn fptr;
    };
    So now there is a member variable of type "ptrFn" called fptr.

    In main()
    Code:
    int main()
    {
        X myx;
        char *a;
        DWORD b;
        byte c;
        X::ptrFn fn = myx.fptr;
        (myx.*fn)(a, b, c); 
    }
    This now compiles. Note how the expression is broken up in main() to see how this all works.

    Now, you can do a substitution:
    Code:
    int main()
    {
        X myx;
        char *a;
        DWORD b;
        byte c;
        (myx.*(myx.fptr))(a, b, c); 
    }
    This now compiles. All I did was substitute back into the expression the declaration of "fn".

    Regards,

    Paul McKenzie

  3. #3
    Join Date
    Jul 2005
    Location
    Netherlands
    Posts
    2,042

    Re: Member function pointer to a member function

    Cheers, D Drmmr

    Please put [code][/code] tags around your code to preserve indentation and make it more readable.

    As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured