Search code examples
c++staticlnk2001

Is it possible to initialize static fields within a static function?


I want something that looks like this...:

class Foo {
public:
  static void myStaticInit();
  static SomeType myField;
};

And inside .cpp:

#include "SomeOtherFile.h" // contains SomeOtherType

void Foo::myStaticInit() {
  SomeOtherType sot;
  myField = sot.someNonStaticFunction(); // also tried Foo::myField = ...
}

... so that I can make calls like Foo::myField. But all I get are LNK2001 errors.

Is such a design possible? Or do I have to provide individual definitions outside a function within .cpp?


Solution

  • When you declare static variables, you also have to define them. In your cpp file, after the Foo declaration, add this line:

    SomeType Foo::myField;
    

    Then, your init function should work.


    Also note that you can initialize it directly by defining it like this:

    SomeOtherType sot;
    SomeType Foo::myField = sot.someNonStaticFunction();
    

    or :

    SomeType Foo::myField = SomeOtherType().someNonStaticFunction();