class Foo { public: Foo() { do_something = &Foo::func_x; } int (Foo::*do_something)(int); // function pointer to class member function void setFunc(bool e) { do_something = e ? &Foo::func_x : &Foo::func_y; } private: int func_x(int m) { return m *= 5; } int func_y(int n) { return n *= 6; } }; int main() { Foo f; f.setFunc(false); return (f.*do_something)(5); // <- Not ok. Compile error. }
How can I get this to work?
A class can have non-static member functions, which operate on individual instances of the class. class CL { public: void member_function() {} }; These functions are called on an instance of the class, like so: CL instance; instance.
The compiler supplies a special implicit pointer named this that allows a member function to access the non- static data members. The this pointer contains the address of the object that called the member function.
First, because static member functions are not attached to an object, they have no this pointer! This makes sense when you think about it -- the this pointer always points to the object that the member function is working on. Static member functions do not work on an object, so the this pointer is not needed.
Pointers to members allow you to refer to nonstatic members of class objects. You cannot use a pointer to member to point to a static class member because the address of a static member is not associated with any particular object.
class A{ public: typedef int (A::*method)(); method p; A(){ p = &A::foo; (this->*p)(); // <- trick 1, inner call } int foo(){ printf("foo\n"); return 0; } }; void main() { A a; (a.*a.p)(); // <- trick 2, outer call }
The line you want is
return (f.*f.do_something)(5);
(That compiles -- I've tried it)
"*f.do_something
" refers to the pointer itself --- "f" tells us where to get the do_something value from. But we still need to give an object that will be the this pointer when we call the function. That's why we need the "f.
" prefix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With