After asking this question, I just wondered is there any language that has this concept. Consider this piece of arbitrary code:
class Foo {
void bar() {
static int i = 0;
print(i++);
}
}
Foo foo = new Foo();
foo.bar(); // prints 0
foo.bar(); // prints 1
Foo foo2 = new Foo();
foo2.bar(); // prints 2
foo2.bar(); // prints 3
So the static i
variable shared across all instances of Foo class and it's life time starts at first encounter and lasts all program long. What I wonder is, is there any language that has some_magic_keyword
for defining a variable, that makes the variable function scoped and makes it life time equal to it's class life time and not sharing it along the instances of the class. So the code can be something like this:
class Foo {
void bar() {
some_magic_keyword int i = 0;
print(i++);
}
}
Foo foo = new Foo();
foo.bar(); // prints 0
foo.bar(); // prints 1
Foo foo2 = new Foo();
foo2.bar(); // prints 0
foo2.bar(); // prints 1
delete foo2; // the "i" variable is also deleted from memory, so no memory leaks
There is some questions about if we can implement this in some particular language but I couldn't find any asking if any language has it. And it doesn't have to be an object oriented language, I can't think of any functional language with this concept for obvious reasons but if you can make the analogy, why not?
EDIT: If there isn't any which seems like, why not? I mean the concept is pretty straightforward. Actually when I first used a static variable in a function, I was expecting the same behaviour I'm asking here.