Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

int f(char) {
    return 0;
}

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

No, seriously, use a typedef :)


#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;
}

Create a typedef for the function signature:

typedef void (* FuncSig)(int param);

Then declare your function as returning FuncSig:

FuncSig GetFunction();

Assuming int f(char) and ret_f which returns &f.

C++98/C++03 compatible ways:

  • Ugly way:

    int (*ret_f()) (char) { return &f; }
    
  • With typedef:

    typedef int (sig)(char);
    
    sig* ret_f() { return &f; }
    

    or:

    typedef int (*sig_ptr)(char);
    
    sig_ptr ret_f() { return &f; }
    

Since C++11, in addition we have:

  • with decltype:

    decltype(&f) ret_f() { return &f; }
    
  • trailing return type:

    auto ret_f() -> int(*)(char) { return &f; }
    

    or:

    auto ret_f() -> decltype(&f) { return &f; }
    
  • typedef with using:

    using sig = int(char);
    
    sig* ret_f() { return &f; }
    

    or:

    using sig_ptr = int (*)(char);
    
    sig_ptr ret_f() { return &f; }
    

C++14 adds:

  • auto deduction:

    auto ret_f() { return &f; }
    

In C++11 you can use trailing return types to simplify the syntax, e.g. assuming a function:

int c(int d) { return d * 2; }

This can be returned from a function (that takes a double to show that):

int (*foo(double e))(int)
{
    e;
    return c;
}

Using a trailing return type, this becomes a bit easier to read:

auto foo2(double e) -> int(*)(int)
{
    e;
    return c;
}

Here is how to do it without using a typedef:

int c(){ return 0; }

int (* foo (void))(){  //compiles
return c;
}

Syntax for returning the function:

return_type_of_returning_function (*function_name_which_returns_function)(actual_function_parameters) (returning_function_parameters)

Eg: Consider the function that need to be returned as follows,

void* (iNeedToBeReturend)(double iNeedToBeReturend_par)
{
}

Now the iNeedToBeReturend function can be returned as

void* (*iAmGoingToReturn(int iAmGoingToReturn_par))(double)
{
   return iNeedToBeReturend;
}

I Felt very bad to learn this concept after 3 years of professional programming life.

Bonus for you waiting down for dereferencing function pointer.

C++ Interview questions

Example for function which returns the function pointer is dlopen in dynamic library in c++