-1

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?

Beko
  • 982
  • 3
  • 15
  • 26

1 Answers1

1

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();
Sid S
  • 6,037
  • 2
  • 18
  • 24