I am reviewing some code I downloaded, and I see the following:
class MyClass
{
[...]
public:
static double shape;
[...]
};
double MyClass::shape = 1.0;
It seems strange that the type is declared twice. Why is this necessary?
I am reviewing some code I downloaded, and I see the following:
class MyClass
{
[...]
public:
static double shape;
[...]
};
double MyClass::shape = 1.0;
It seems strange that the type is declared twice. Why is this necessary?
The declaration in the class definition, is a pure declaration.
The declaration after the class definition, is a definition. It allocates storage for the variable.
One reason to do it that way is that for static
data members only those of integral or enum
types, or constexpr
, or C++17 inline
, can be initialized in the in-class declaration.
A definition like the above should not be placed in a header file, because if that header is included in more than one translation the multiple definitions will violate the One Definition Rule.
One simple solution is to replace the direct static
variable with an accessor function:
// OK to place in a header:
class MyClass
{
public:
static auto shape()
-> double&
{
static double the_shape = 1.0;
return the_shape;
}
};