Search code examples
c++c++11function-pointersdereferencestd-function

How to call a function returning a function pointer?


I am trying to call a function pointer using an explicit dereference. But the compiler throws an error:

no operator "*" matches these operands.

Here's a simplified version of my code:

#include <functional>
#include <iostream>

int add(int a, int b)
{
    return a + b;
}

std::function<int(int, int)> passFunction()
{
    return &add;
}

int main()
{
    int a{ 1 };
    int b{ 2 };

    std::cout << (*passFunction())(a, b);
    return 0;
}

The thing is, it works fine when I just write:

std::cout << passFunction()(a, b); // without asterix. 

which blows my mind.

I thought that, I messed up parentheses in function call. I tried different order and precedence, I called it with ampersand, and still compiler doesn't even flinch.


Solution

  • I'm trying to call a pointer function using a explicit dereference. But compiler throws an error: 'no operator "*" matches these operands'.

    Type matters!

    The return type of the passFunction is not a pointer, rather std::function. It is not something of dereferencable. Hence, you get the compiler error.


    The thing is, it works fine when I just write: std::cout << passFunction()(a, b); without asterix [...]

    The std::function meant for invoking/ calling. That is why passFunction()(a, b) works. It calls the operator() of std::function (i.e. equivalent to passFunction().operator()(a, b)).

    That been said, if you simply return the function by auto (since C++14 - let the compiler deduce the type), you will get the actual function pointer, which you can call either by dereferencing (unnecessary) or directly.

    using fun_t = int(*)(int, int); // function pointer type
    
    auto passFunction()
    //^^^ use auto --> type ==  int(*)(int, int)
    // or use fun_t
    {
        return &add;
    }
    

    now you can (unnecessary)

    (*passFunction())(a, b);
    

    or

    passFunction()(a, b);
    

    Now obvious question, "how the both syntax is possible ?". Read here in detail in the following posts: