How to make a function return a pointer to a function? (C++)


Question

I'm trying to make a function that takes a character, then returns a pointer to a function depending on what the character was. I just am not sure how to make a function return a pointer to a function.

1
63
7/17/2009 8:15:06 PM

Accepted Answer

#include <iostream>
using namespace std;

int f1() {
    return 1;
}

int f2() {
    return 2;
}

typedef int (*fptr)();


fptr f( char c ) {
    if ( c == '1' ) {
        return f1;
    }
    else {
        return f2;
    }
}

int main() {
    char c = '1';
    fptr fp = f( c );
    cout << fp() << endl;
}
68
6/15/2009 7:15:28 PM

int f(char) {
    return 0;
}

int (*return_f())(char) {
    return f;
}

No, seriously, use a typedef :)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon