I have some confusion about how to use a pointer to a member function that is a member data itself:
struct Foo
{
void bar(int x)
{
cout << x << endl;
}
double getVal(double d)
{
return ++d;
}
void(Foo::*pMemFunc)(int) = &Foo::bar;// ptr to mem func
int(Foo::*pMemI) = &Foo::val_;// ptr to mem data
int* pI = &val_;
int val_ = 57;
};
int main()
{
Foo f, *pF = new Foo{};
double(Foo::*pMemFun)(double) =
&Foo::getVal;
cout << (f.*pMemFun)(3.14) << endl;// dereferencing a pMemFun yields a the member getVal so we need an object or pointer to call it.
cout << (pF->*pMemFun)(2.08) << endl;// through pointer to Foo obj
f.Foo::pMemFunc = &Foo::bar;
// f.Foo::pMemFunc(5);// how to use this?
cout << "\nDone!\n";
}
So pMemFunc
is a pointer to a member function but the pointer itself is a member data of class Foo
so how can I call the member function it points to it?
I've tried something like this:
f.(*f.pMemFunc)(0);
But it doesn't work. What I find harder is that accessing that member must be through an object e.g f.pMemFunc
or pF->pMemFunc
then dereferencing it yields a member function which needs an object to call it so I try: f.(*f.pMemFunc)(10);
but I get compile-time error.
Please explain how to do it. Thank you!
I finally somehow get it work aftet a lot of attempts: break the exppresion into to parts:
auto ret = f.pMemFunc; // 1 (f.*ret)(0);// 2. works fine
But please explain why now it works and what happens?!