how to take Address of a Member Function in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lovetopravin
    New Member
    • Oct 2013
    • 16

    how to take Address of a Member Function in C++

    I want to take address of a member function in c++.
    how to do this.
    please suggest me as soon as possible.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Something like this

    Code:
    class Example
    {
    public:
      int function(double);
    }
    
    int main()
    {
      // Declare memFunPtr, pointer to a member function
      int (Example::*memFunPtr)(double) = &Example::function;
    
      // Use the member function pointer
    
      int result;
      double input = 5.0;
      Example e;
    
      result = (e.*memFunPtr)(input);
    }
    To avoid syntax errors it is a good idea to typedef your member function pointer type

    Code:
    class Example
      typedef int (Example::*MemFunPtr_t)(double);
    
      MemFunPtr_t memFunPtr2 = &Example::function;
    Last edited by Banfa; Oct 23 '13, 01:11 PM.

    Comment

    • lovetopravin
      New Member
      • Oct 2013
      • 16

      #3
      sir actually i havn't got your point.
      So please explain in detail.
      Suppose A is a class and Display is a Member function of class A. if i want to see the address of Display member function then why i can't write like below code.
      Code:
      A obj;
      cout<<&obj.Display();
      why it gives error.

      Comment

      Working...