Why field inside a local class cannot be static?

Because nobody saw any need for it ?

[edit]: static variables need be defined only once, generally outside of the class (except for built-ins). Allowing them within a local class would require designing a way to define them also. [/edit]

Any feature added to a language has a cost:

  • it must be implemented by the compiler
  • it must be maintained in the compiler (and may introduce bugs, even in other features)
  • it lives in the compiler (and thus may cause some slow down even when unused)

Sometimes, not implementing a feature is the right decision.

Local functions, and classes, add difficulty already to the language, for little gain: they can be avoided with static functions and unnamed namespaces.

Frankly, if I had to make the decision, I'd remove them entirely: they just clutter the grammar.

A single example: The Most Vexing Parse.


Magnus Skog has given the real answer: a static data member is just a declaration; the object must be defined elsewhere, at namespace scope, and the class definition isn't visible at namespace scope.

Note that this restriction only applies to static data members. Which means that there is a simple work-around:

class Local
{
    static int& static_i()
    {
        static int value;
        return value;
    }
};

This provides you with exactly the same functionality, at the cost of using the function syntax to access it.


Because, static members of a class need to be defined in global a scope, e.g.

foo.h

class A {
  static int dude;
};

foo.cpp

int A::dude = 314;

Since the scope inside void foo(int x) is local to that function, there is no scope to define its static member[s].