Consider this code:
class Foo {
private:
static char buffer[];
};
char Foo::buffer[100];
Is this valid, or do I need to put buffer[100]
also in the class definition?
A non-inline static data member declared in a class may have an incomplete type.
From the C++ 17 Standard (12.2.3.2 Static data members)
2 The declaration of a non-inline static data member in its class definition is not a definition and may be of an incomplete type other than cv void. The definition for a static data member that is not defined inline in the class definition shall appear in a namespace scope enclosing the member’s class definition. In the definition at namespace scope, the name of the static data member shall be qualified by its class name using the :: operator. The initializer expression in the definition of a static data member is in the scope of its class (6.3.7).
So as this declaration (where there is a typo: the type specifies char
is present twice) in the class definition
static char char buffer[];
is not a definition (of an inline data member) it may have an incomplete character array type.
On the other hand, if you want to refer to the array within the class definition it is better to declare it as a complete type. For example this class definition
class Foo
{
public:
void f() const
{
std::cout << std::size( buffer ) << '\n';
}
private:
static char buffer[];
};
will not compile because within the function f
in this expression std::size( buffer )
there is used an incomplete array type.