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

mpandey's Avatar
Newbie Member
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;
}
0
Gene Poole's Avatar, Join Date: Nov 2009
Contributor
Did you have a question?
0
mpandey's Avatar
Newbie Member
the Question is
want to know how to return address of a member function of a class (tAdd and tSubtract in this case) ?
0
Gene Poole's Avatar, Join Date: Nov 2009
Contributor
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.