I was reading about delegation and I wanted to able to call with a base class a any function pass as parameter depending on the event, I did it this way and it works but I am not sure if it is the proper way and if it is portable like this.
class base {
public:
typedef void (base::*methodPTR)();
methodPTR pfn;
void setMethod(methodPTR fn)
{
pfn = fn;
}
void run(){
if(pfn) (this->*pfn)();
}
};
class a : public base {
public:
void fn()
{
cout<<"from class a!"<<endl;
}
};
class b : public base
{
a ob;
public:
void init()
{
ob.setMethod(static_cast<base::methodPTR>(&b::fn));
}
void fn()
{
cout << "from class b!" << endl;
}
void test()
{
ob.run();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
b x;
x.init();
x.test();
return 0;
}
You are calling the member function
fnof classbwith an instance of classawhich will cause undefineded behaviour if you access data memebers of your class.Replace your classes
aandbwith this to see the magic :