Static class variable initialisation in C++

I’ve been trying to make a simple Service Locator class work but had a problem with bizarre linker errors, where the static member variable couldn’t be resolved.

After a lot of head scratching, fiddling and Googling I came across this website that explained it.

It’s fairly simple, if you have a class like this:

class foo {
  static int memberVar;
  ...
};

you need to declare the member variable elsewhere, inside a real C++ file (not a header). Code like this will work:

static int foo::memberVar;

It’s a bit strange, but then again so are static classes.

About James

If this were the 80s I'd be sat in front of a C64 or Speccy, or taking VCRs apart.