Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a member of a class be named the same name as its type (another class)?

Trying to compile the following code on different compilers gives me two different results:

struct S{};
struct T{S S;};
int main(){}

As you can see, inside T, I have an object named the same as the previously defined class S.


On GCC 4.7.2, I get the following error pertaining to the S S; declaration inside T:

error: declaration of 'S T::S' [-fpermissive]
error: changes meaning of 'S' from 'struct S' [-fpermissive]

However, moving it outside of the class (or into main) works fine:

struct S{};
S S;
int main(){}

What exactly does it mean by the error it's giving me?


In Visual Studio 2012, the whole thing compiles and runs without any errors. Pasting it into this Clang 3.0 compiler gives me no errors as well.

Which is right? Can I actually do this or not?

like image 348
chris Avatar asked Oct 17 '12 21:10

chris


People also ask

Can 2 classes have same name in C++?

Both declare classes with the same name, but perhaps a totally different structure (or perhaps the same structure, different implementation). The classes do not appear in the header files. (As an example, suppose they are Node classes for different list classes.)

Can two classes have member functions with the same name?

Yes, but only if the two classes have the same name.

Can a class have the same name as a namespace?

Inside a namespace, no two classes can have the same name.

Can a function have the same name as a class?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur.


2 Answers

gcc is correct, from [3.3.7 Class Scope]

A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

However, note that no diagnostic is required, so all compilers are conforming.

The reason is because of how class scope works. When you write S S; S is visible within the entire class and changes the meaning when you use S.

struct S{};
struct T{
    void foo()
    { 
        S myS; // Not possible anymore because S refers to local S
    }
    S S;
};
like image 188
Jesse Good Avatar answered Sep 30 '22 19:09

Jesse Good


@JesseGood provide a complete answer, but if you really want to do this without any error, you can use type's full name and it will work as follow:

struct S {};
struct T { ::S S; };
int main() {return 0;}

No there is no error, since S in your class is T::S and its type is ::S!

like image 31
BigBoss Avatar answered Sep 30 '22 19:09

BigBoss