Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function pointer (class member) to non-static member function

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?

like image 336
Girish Avatar asked Jun 13 '09 12:06

Girish


People also ask

Can a static member function call non-static member function of a class?

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.

Which pointer is present inside every non-static member function?

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.

Why static member functions do not get this pointer?

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.

Is it possible to create a pointer to member function of any class?

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.


2 Answers

 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     } 
like image 64
Nick Dandoulakis Avatar answered Oct 14 '22 10:10

Nick Dandoulakis


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.

like image 34
James Curran Avatar answered Oct 14 '22 10:10

James Curran