Search code examples
c++functionvisibilityoverload-resolution

member function hiding free function


void foo(int)
{
}

class X
{
    void foo()
    {
    }

    void bar()
    {
        foo(42);
        // error: no matching function for call to 'X::foo(int)'
        // note: candidate is:
        // note: void X::foo()
        // note:   candidate expects 0 arguments, 1 provided        
    }
};

Why is C++ unable to call the free function (which is the only one with the correct signature)?


Solution

  • The logical reason is Consistency.

    • Suppose as per the suggestion, compiler resolves foo(42) to ::foo(int).
    • Now after sometime, if you change X::foo() to X::foo(int) then foo(42) will be resolved to X::foo(int). Which is not consistent.

    That is the also the reason why derived class function hides base class function when there are similar names.

    Such cases can be resolved in 2 ways;

    (1) Give fully qualified name (e.g. ::foo(42))

    (2) Use using utility; e.g.

    void bar()
    {
      using ::foo;
      foo(42);
    }