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;
};
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Your code is legal, if MS VC++ says otherwise then it is wrong.
In C++11, 9.2/16:
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 namedtest, 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: