Search code examples
c++functionfunctor

Compiler chooses functor over function with same name


Can someone please explain what rule determines that the compiler calls the functor f below instead of the function f?

#include <iostream>

struct A {
    void operator()() { std::cout << "functor" << std::endl; }
};

void f() { std::cout << "function" << std::endl; }

int main()  
{
    A f;
    f();  // Output: functor
}

A::operator()() and f() are not overloads, so my guess is this happens outside of overload resolution.


Solution

  • That's due to name hiding. When you declare the f variable, it hides the f function. Any use of the name f in that scope will refer to the local variable rather than the function.

    If you want to call the function f, then you could use the scope resolution operator:

    #include <iostream>
    
    struct A {
        void operator()() { std::cout << "functor" << std::endl; }
    };
    
    void f() { std::cout << "function" << std::endl; }
    
    int main()  
    {
        A f;
        ::f();  // Output: function
    }