Static variables in member functions

monofonik picture monofonik · Jun 3, 2011 · Viewed 87.1k times · Source

Can someone please explain how static variables in member functions work in C++.

Given the following class:

class A {
   void foo() {
      static int i;
      i++;
   }
}

If I declare multiple instances of A, does calling foo() on one instance increment the static variable i on all instances? Or only the one it was called on?

I assumed that each instance would have its own copy of i, but stepping through some code I have seems to indicate otherwise.

Answer

iammilind picture iammilind · Jun 3, 2011

Since class A is a non-template class and A::foo() is a non-template function. There will be only one copy of static int i inside the program.

Any instance of A object will affect the same i and lifetime of i will remain through out the program. To add an example:

A o1, o2, o3;
o1.foo(); // i = 1
o2.foo(); // i = 2
o3.foo(); // i = 3
o1.foo(); // i = 4