Click to See Complete Forum and Search --> : Function pointer - 2


flotat
April 19th, 1999, 02:38 AM
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.

Paul McKenzie
April 19th, 1999, 03:23 AM
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

flotat
April 19th, 1999, 05:43 AM
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.