user6394951
user6394951

Reputation:

C++ member function overloading picks wrong function

MSVC throws error C2660 when trying to overload a global function as a member function (with different number of arguments) that calls the global function in it's body.

This code:

void f(int* x, int y) { *x += y; }

struct A
{
    int* x;
    inline void f(int y)
    {
        f(x, y); // tries to call A::f instead of f
    }

    void u(void)
    {
        f(5);
    }
};

gives this error:

error C2660: 'A::f' : function does not take 2 arguments

Upvotes: 2

Views: 715

Answers (2)

Barry
Barry

Reputation: 303087

Unqualified name lookup on f will start at the narrowest scope and work its way outward. When we find A::f, we stop: we already found what we were looking for. We don't keep going. Moreover, since A::f is a class member, we don't even perform argument dependent lookup - we simply stop.

To call ::f, you need to use a qualified call:

::f(x,y);

You might think that this problem might be solved with a using-declaration:

using ::f;
f(x,y);

This works in this case. However, we're still not overloading the two fs; any attempt to call the member function will fail for the same reason: ::f will be found first and then we stop.

Upvotes: 6

Jarod42
Jarod42

Reputation: 217283

Use ::f(x, y); to use the one in global namespace.

Upvotes: 2

Related Questions