3

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.

Community
  • 1
  • 1
isamert
  • 482
  • 4
  • 12
  • I may be missing the point, but are you not asking for a member variable? – sji Jul 13 '16 at 14:54
  • 1
    Yes it's exactly does what a member variable does but the syntax is as I mentioned. So it's function scoped. – isamert Jul 13 '16 at 14:55
  • 1
    Ah I understand, thanks – sji Jul 13 '16 at 14:57
  • 4
    As for "if not why not": because a member attribute does exactly the same thing, except for being function scoped, which is simply a matter of accessing your member attribute only within one specific function. Introducing new syntax and supporting a new feature just for that seems like more work than it's worth. – What specifically would be the advantage of this over a member which you're only using in one specific function context? – deceze Jul 13 '16 at 15:20

0 Answers0