views:

66

answers:

3
class Foo
{
public:
    void bar();
};

void Foo::bar()
{
    static int n = 0;

    printf("%d\n", n++);
}

int main(int argc, char **argv)
{
    Foo *f = new Foo();
    f->bar();
    delete f;
    f = new Foo();
    f->bar();
    delete f;

    return 0;
}

Does n reset to 0 after delete'ing and new'ing the class over again? Or is n effectively a static class member (same reference in all instances)?

In other words, should I get

0
0

or

0
1

?

+2  A: 

As the variable is static in the function, it will be 0, 1 as the memory is not delete as it is static, even if the variable is part of a function and not part of the class.

Even when you delete an instance of a class, the functions still remain in memory for the class as they can be used by other instances of the class.

Glenn
That makes sense. So the static local really is the same for all class instances, because they are really all using the same function instance.
jgottula
A: 

0 1

'n' is effectively a static class member with a different scope. Its essentially the same as a static variable in a function of any other context (member function, global, etc)

turdfurguson
A: 

'n' is a static variable in the function Foo::bar. There is only ever one copy of that function, regardless of how many Foo instances you might create or destroy.

aem