So I have this problem for a while now. I just couldn't find the answer to the question. Why do I have to give the data type twice while using static variables inside a class?
Here's an example:
#include <iostream>
class Test{
public:
static int test;
};
//right here is the point of confusion
int Test::test = 10;
int main(){
Test test;
std::cout << test.test << "\n";
}
As you can see from my program above I had to initialize the variable this way. But what about the duplicate data type specification? Why did I have to write the "int" data type twice? Once already in the class and then again? What is the underlying reason? Thanks for any help in advance.
CodePudding user response:
You don't 'have to' duplicate as long as you provide the type somehow. Grammar requires a type there that cannot be auto (which is not type, but usually people expect to be able to write it in place of a type), but you can still let the compiler deduce it:
#include <iostream>
class Test{
public:
static int test;
};
//right here is the point of confusion
decltype(Test::test) Test::test = 10;
int main(){
Test test;
std::cout << test.test << "\n";
}
If you don't like duplicating type name, you might write a macro for it.
CodePudding user response:
Why did I have to write the "int" data type twice?
Because there are 3 components of a simple-declaration
, namely attributes
, specifiers
and declarators
and a definition(like the one you provided) is also a declaration so it has to follow these rules. Now, the second of these component, specifier
indicate the type, storage class or other properties of the entity that is being declared and is not optional.
This means that when providing the definition for the static data member, you still need to provide the type-specifier
according to the grammar. This also means that you can use decltype(Test::test)
instead of int
when defining the static data member outside the class.
The point is that the current grammar requires us to specify the type
when defining.