Search code examples
c++ambiguityambiguous-call

What happens when a class and a function have the same name?


#include <iostream>
using namespace std;

struct test
{
    test(){cout<<"class"<<endl;}
};
void test(){cout<<"function"<<endl;}

int main()
{
    test();
    return 0;
}

Output:

function  

(VS2013 ang gcc 4.8.1)

Why function is selected? Isn't it ambiguity?


Solution

  • This is called name hiding and described in

    3.3 Scope [basic.scope]

    3.3.1 Declarative regions and scopes [basic.scope.declarative]

    4) Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,
    — they shall all refer to the same entity, or all refer to functions and function templates; or
    — exactly one declaration shall declare a class name or enumeration name that is not a typedef name and the other declarations shall all refer to the same variable or enumerator, or all refer to functions and function templates; in this case the class name or enumeration name is hidden (3.3.10). [...]

    emphasis mine.

    Note that changing the order of declaration doesn't affect the outcome:

    void test(){cout<<"function"<<endl;}
    
    struct test
    {
        test(){cout<<"class"<<endl;}
    };
    
    int main()
    {
        test();
        return 0;
    }
    

    still prints out function.

    In case it isn't obvious, don't do this :)