16

Is declaring a static field of a type that is incomplete at the moment of the class definition legal in C++? For example:

Foo.h:

class Foo
{
public:
  // ...
private:
  class Bar;
  static Bar something;
};

Foo.cpp:

class Foo::Bar
{
  // ...
};

Foo::Bar Foo::something;

// some more code

Compilers seem to accept it, and I don't see a reason for which it should be rejected, but what does the standard say about such situation? I'd really appreciate someone giving a direct quote from the standard, preferably from the "old" one (the one from 2003).

2 Answers2

14

Yes, what you're doing is specifically allowed (§9.4.2/2): "The declaration of a static data member in its class definition is not a definition and may be of an incomplete type other than cv-qualified void."

Jerry Coffin
  • 437,173
  • 71
  • 570
  • 1,035
3

I can't quote from the standard, but I can give you the advice to "think like a compiler".

At the point that you're declaring something, what does the compiler need to know about the type? If it were a normal member it would need to know the size so that it could include it in the class definition, but that's not true for static members because their storage is not part of the class. It doesn't need to know how to construct it because it won't be constructed as part of class construction. There really isn't anything the compiler needs to know about that static class at the time it's declared, so a forward declaration works just fine.

Mark Ransom
  • 271,357
  • 39
  • 345
  • 578
  • 1
    Yup. That's why I said "I don't see a reason for which it should be rejected". I'm know the things you've written, I just wasn't sure if the standard doesn't disallow code like that for some reason (it's C++, you can never be sure), that's why I wanted a direct quote. Besides, I had to ask my first question here ;) –  Nov 09 '11 at 17:31