#include
using namespace std;
struct A
{
A()
{
cout << "A::A()" << endl;
}
};
int A()
{
cout << "void A()" << endl;
return 0;
}
int main()
{
auto v = A();
}
The output is:
void A()
Why does C++ allow a function and a class have a same name?
Solved
I believe this comes down to backwards compatibility with C.
In C, when you declare a struct like you did, you then have to refer to it as struct A, not just A. For example:
void A() {}
struct A {};
void f()
{
A();
struct A x; // works fine
A y; // does not compile
}
In this context, it makes sense to allow A to mean two different things, because it's always clear which one you mean, depending on whether you used struct or not.
In C++, structs (and classes) can be referenced directly, without the need to use the struct keyword. This introduces the ambiguity you're concerned about, but the alternative is that valid C code like the one above would not be valid C++ code, which is even worse.
Why? Because that's the way the language is! The A::A() function belongs in a different "domain" than A().
It's similar to namespaces, where the same name can exist in multiple domains.
It's also somewhat similar to having a thousand different functions (or scopes) all having their own loop counter called i.
Comments
Post a Comment