Having a class static method with same name as another class
-
30-09-2019 - |
Question
Here is the example :
struct A
{
A(const int a ):b(a)
{
}
int b;
};
struct B
{
B() : a(5)
{
}
static void A()
{
}
A a;
};
int main()
{
B::A();
}
And the compiler error is :
a9.cpp:19: error: ‘A’ does not name a type
a9.cpp: In constructor ‘B::B()’:
a9.cpp:24: error: class ‘B’ does not have any field named ‘a’
I am using gcc 4.3.0 on fedora 9.
Can someone explains why is the compiler complaining? If possible, with references from the standard.
Thanks
Solution
This works:
struct B {
B() : a(5) { }
static void A() { }
::A a;
};
Since you've used A
as a member name in B
, that member's definition shadows the A
type from the outer namespace. Using ::
you can get to that namespace.
This behavior is specified in the (draft) standard as:
3.3.7 (1) "A name can be hidden by an explicit declaration of that same name in a nested declarative region" (the definition of struct B
, which is nested in the namespace where struct A
is also defined).
Carefully read the introduction to chapter 3, Basic concepts, for further clarification. Especially, this section specifies that
3 (7) Two names are the same if
- they are identifiers composed of the same character sequence; or
- they are the names of overloaded operator functions formed with the same operator; or
- they are the names of user-defined conversion functions formed with the same type.
Note that this last definition does not distinguish between types and class members, so the name hiding (shadowing) rule 3.3.7 (1) applies.