Variable with same class name?

What are the reasons behind that we can not declare and define a variable(property) inside a class with the same name of the class itself? For example this code is not right(at least in MS VC++):

class test{

public:
int test;

};

Answers


Your code is legal, if MS VC++ says otherwise then it is wrong.

In C++11, 9.2/16:

In addition, if class T has a user-declared constructor (12.1), every non-static data member of class T shall have a name different from T.

Your class does not have a user-declared constructor, and the data member you define is non-static, so it can be named test. If it were static, then 9.2/15 says it can't be named test, but 9.2/15 says nothing about non-static data members.

In C++03, it's 9.2/13 and /13a, the rules are the same.

If MS VC++ issues a warning, then that's probably justified. The effect of your data member makes more sense to C programmers than to C++ programmers:

struct test{
    void foo(test &a) {   // "test" is a type here
        struct test t;    // "test is not a type here, "struct test" is
        a = t;
    }
    int test;
};

struct test{
    int test;
    void foo(struct test &a) {   // now "test" is not a type here either
        struct test t;
        a = t;
    }
};

Need Your Help

what is the meaning of a UDP “blocking socket” when it comes to receiving data through it?

udp

I get the return value of the read operation as 0 if the sockets is non blocking, and the real number of bytes read if the socket is marked as blocking. cant understand why though ...

Combining Trees and Nodes, value unaccessible

c binary-tree

i'm experimenting with trees and nodes and I having trouble.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.