2

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?

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • [Declarations of variable inside the class may have incomplete type.](https://stackoverflow.com/questions/70683050/how-am-i-able-to-use-a-class-as-a-function-parameter-in-itself). So this is valid. – Jason Apr 16 '23 at 15:38

2 Answers2

3

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Is this valid

Yes this is valid since for buffer you have a declaration that is not a definition inside the class. This can be seen from static member's documentation:

The declaration inside the class body is not a definition and may declare the member to be of incomplete type (other than void), including the type in which the member is declared.

This means that buffer can have incomplete type such as char[] in its declaration inside the class.

Jason
  • 36,170
  • 5
  • 26
  • 60