Wednesday, January 7, 2009

static variables in a C++ class

Certainly mature methods of software coding recommend that you avoid global variables. So sometimes you end up using static data members within C++.

I recently learned this about using static variables in C++ classes. You need to define the static data member outside the class declaration. Failure to do this results in a linker error, the reason being because without the definition the compiler doesn't know which translation unit (hence object file) the member is supposed to go.

Sample code:

class bar {
int getBar1();
static int bar1;

#include "foo.h"

int bar::bar1;

One more reason why I don't consider myself a C++ programmer.

No comments: