Function Pointer Issue  
Author Message
UnKnown Nick

PostPosted: Visual C++ Language, Function Pointer Issue Top

Following is the piece of code I am using in an application.

#include <iostream.h>

class Temp
void foo(){cout<<"foo called"<<endl;}
void foo1(int x){cout<<"foo1 called with x "<<x<<endl;}
void TestingMethod();
void (Temp::*Ptr2Func)(void);

void Temp::TestingMethod()
Ptr2Func = foo;

void main()
Temp A;
I get the error: error C2171: '*' : illegal on operands of type 'void (__thiscall Temp::*)(void)'
However If I replace it with:
(this->*Ptr2Func)();, it works fine.

I want to understand the reason of this behaviour. Can someone please help me

Visual C++11  
Alex Farber

PostPosted: Visual C++ Language, Function Pointer Issue Top

This is the way pointers to class functions are implemented in C++.

Ptr2Func = foo; // this means, Ptr2Func can point to foo function in any class instance

(this->*Ptr2Func)();, // call foo in "this" class instance

You may think that if Ptr2Func isTemp class member, it must always point to function of "this" instance. But this is not correct, it can point to function in any class instance, and you need to specify instance using Ptr2Func pointer.