1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

is it possible to return a function pointer which is a member of a class

Discussion in 'C++' started by mpandey, Nov 13, 2009.

  1. mpandey

    mpandey New Member

    Joined:
    Nov 13, 2009
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    elaborating more;-

    the Fptr which is returned from the function points to a function which is a member function of a class

    Code:
    //compiled using devcpp (GCC compiler)
    //this code shows how to return address of global function (add and subtract)
    //want to know how to return address of a member function of a class (tAdd and tSubtract)
    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    int add(int a, int b);
    int subtract(int a,int b);
    
    class Temp
    {
     public:
            int tAdd(int,int);
            int tSubtract(int,int);
    //getFPtr will take a const char and return a function pointer 
            int (*getFPtr(const char opcode))(int,int);
     };
    
    int main(int argc, char *argv[])
    {
        Temp t;
        cout<<(t.getFPtr('-'))(20,10);//calling a function which returns a fptr
        
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    
    int (*Temp::getFPtr(const char opcode))(int,int)
    {
         cout<<"int (*Temp::getFPtr(const char opcode))(int,int)"<<endl;
         if(opcode == '+')
         return &add;
         else if (opcode == '-')
         return &subtract;
    }
    int add(int a, int b)
    {
        return a+b;
    }
    
    int subtract(int a,int b)
    {
        return a-b;
    }
    
    
     
  2. Gene Poole

    Gene Poole New Member

    Joined:
    Nov 10, 2009
    Messages:
    93
    Likes Received:
    5
    Trophy Points:
    0
    Did you have a question?
     
  3. mpandey

    mpandey New Member

    Joined:
    Nov 13, 2009
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    the Question is
    want to know how to return address of a member function of a class (tAdd and tSubtract in this case) ?
     
  4. Gene Poole

    Gene Poole New Member

    Joined:
    Nov 10, 2009
    Messages:
    93
    Likes Received:
    5
    Trophy Points:
    0
    Oh, I see that the question was in the title. Sorry.

    You can do this most easily by declaring tAdd and tSubtract as "static" then they have no implicit "this" pointer and will conform to your prototype.
     

Share This Page