Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   is it possible to return a function pointer which is a member of a class (http://www.go4expert.com/forums/return-function-pointer-class-t20081/)

mpandey 13Nov2009 16:17

is it possible to return a function pointer which is a member of a class
 
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;
}


Gene Poole 13Nov2009 19:11

Re: is it possible to return a function pointer which is a member of a class
 
Did you have a question?

mpandey 13Nov2009 19:17

Re: is it possible to return a function pointer which is a member of a class
 
the Question is
want to know how to return address of a member function of a class (tAdd and tSubtract in this case) ?

Gene Poole 13Nov2009 19:45

Re: is it possible to return a function pointer which is a member of a class
 
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.


All times are GMT +5.5. The time now is 03:49.