Search code examples
c++staticinitializationprivatefriend

How to initialize a static field of which type is a private nested class?


Outer.hpp:

class Outer {
  class Inner {
    Inner() {}
  };
  static Inner inner;
}

Outer.cpp (at top-level, e.g. not within a function body):

Outer::Inner Outer::inner;

I get the following error:

error C2248: 'Outer::Inner::inner' : cannot access private member declared in class 'Outer::Inner'

I'm not using a compiler that is fully compliant with C++11 (Visual Studio 2010), so it is not possible to define the field at declaration.


Solution

  • The trick is to make Outer a friend of Inner:

    Outer.hpp:

    class Outer {
      class Inner {
        Inner() {}
        friend Outer;
      }
      static Inner inner;
    }
    

    Now, Outer can see Inner's type as if it weren't private even in the implementation file, so the initialization in Outer.cpp succeeds.