Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does static member initialization need to be "typed again"?

Here is the case. Static class memmbers must be initialized before using this class, because static members are not object-dependable. They occupy their own place of storage in the heap. But I am confused about the regulations the initialization has to follow.

The code below explains my concern.

class TEST
{
public:
    ...
    static int val;
    ...
}
//Initialization
//int TEST::val = 1;//This is correct.
TEST::val = 1; //This is wrong, compiler msg: lack of type identifier.
//I think that the val member has been declared as int type.
//So WHY must I redeclare its type again? Or I did just miss something?
like image 808
richard.g Avatar asked Feb 13 '26 01:02

richard.g


1 Answers

Theoretically, nothing prevents C++ designers from letting you skip the type in the definition of the val member. Indeed, the compiler knows the type already, and the syntax that looks like an assignment is not otherwise valid outside functions, so there is nothing to prevent the compiler from implementing this approach.

However, this would make the parser more complicated, because the same construct (an assignment) would have to be interpreted differently based on the context. In other words, the same line

TEST::val = 1;

would mean completely different things inside and outside a function. When used inside a function, this line would be treated as an assignment; when used outside a function, the same line would be treated as a definition.

To make life less complicated, both for themselves and the users of the language, the designers decided to stay with the familiar syntax for definitions, at a small expense of asking the users to repeat themselves.

like image 67
Sergey Kalinichenko Avatar answered Feb 15 '26 15:02

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!