Consider the sample program below:
#include <iostream>
using namespace std;
class test
{
public:
static const float data;
};
float const test::data = 10; // Line1
int main()
{
cout << test::data;
cout << "\n";
return 0;
}
Please note the comment Line1 in the sample code.
Questions:
- Is
Line1doing the initialization of the date memberdata? - Is
Line1the only way to initialize a static const non-integral data member?
It certainly is, as well as providing the definition of the object. Note that this can only be done in a single translation unit, so if the class definition is in a header file, then this should be in a source file.
In C++03 it was. In C++11, any static member of
constliteral type can have an initialiser in the class definition. You still need a definition of the member if it’s “odr-used” (roughly speaking, if you do anything that needs its address, not just its value). In this case, the definition again needs to be in a single translation unit, and must not have an initialiser (since there’s already one in the class definition).