TIL static variables don't work inside class methods

Published September 25, 2012

I recently dealt with a bug report demonstrating a pretty subtle and apparently trivial bug which I tracked down (fortunately pretty quickly) to somewhere completely unexpected. It turned out that a static variable inside a class method was causing two separate objects to behave dependently on each other; totally the opposite to what I'd assumed it would do - I'd assumed each instance would get its own static space. (For what it's worth, this was a caching optimisation that I didn't want to clutter the class scope with.)

I wondered if this was normal behaviour for the static keyword. Explicitly static variables is a leftover from C and most languages sensibly omit it because it's kind of redundant with OOP, and evidently, confusing. But C++ doesn't get that choice, so I wondered what it would do.

Apparently it is normal behaviour:

#include "stdafx.h"
#include <iostream>
using namespace std;

class C {
	int AddOne() {
		static int counter = 0;
		return ++counter;

int _tmain(int argc, _TCHAR* argv[])
	C c1, c2;
	cout << c1.AddOne() << endl;
	cout << c2.AddOne() << endl;
	return 0;