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

    Function pointer - 2

    Hi I'am still having problem to write function pointer. Couldsomeone give me the answer why the following code does'nt compile.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    class Test;

    typedef void (Test::*FUNCPTR)();


    class Test
    {
    public:
    Test() {MyFunc=Testfunction;};
    ~Test() {} ;
    void Testfunction() { printf("It works !!!\n"); };


    FUNCPTR MyFunc;
    };

    int main()
    {
    Test vTest;

    *(vTest.MyFunc)();

    return (0);
    }

    Thanks.



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

    Re: Function pointer - 2

    I haven't run this, but change the main() to this:
    ...
    int main()
    {
    Test vTest;
    (vTest.*(vTest.MyFunc))();

    return (0);
    }
    ...

    The reason for the syntax is that the pointer to member is in general:

    (object.*(pointer to member function))(...);

    Invokes the call. In your example, you are attempting to invoke the call from outside the Test class. The "pointer to member function" is (vTest.MyFunc), therefore it needs to be specified this way:

    (vTest.*(vTest.MyFunc))()
    .
    Strange, but this is the way it works in your example.

    If you want to use your original syntax, you have to invoke the function call within a class member function of Test:

    class Test
    {
    public:
    Test() {MyFunc=Testfunction;};
    ~Test() {} ;
    void Testfunction() { printf("It works !!!\n"); };
    void TryThis() { (this->*MyFunc)(); }

    FUNCPTR MyFunc;
    };

    Note that the TryThis() function is a member of the class Test.

    Handling pointers to member functions is one of the biggest headaches of C++. It generates a lot of messages on this board by beginning programmers who are used to C.

    Regards,

    Paul McKenzie


  3. #3
    Join Date
    Apr 1999
    Posts
    12

    Re: Function pointer - 2

    I'd like to very thank you for your help Paul.
    I was really embarassed with C++ Function Pointer syntax (the compiler generates unbelievable error messages).

    Thanks.


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