why we can't declare a static variable incide local class(class inside a function) ?

You can, but static data member definition isn't exactly intuitive without a fairly good understanding of the object model:

class outside
{
public:
      class inside
      {
      public:
            static int x; // Declare as normal
      };
};

// Define using name resolution
int outside::inside::x = 123;

@deceptikon: You misunderstood what the OP was referring to. She is referring to a local class, not a nested class. In other words, this is the case in question:

void f() {
  class inside
  {
    public:
      static int x; // Forbidden!
  };
};

And the explanation for why this is not allowed is that static data members require linkage (be visible to the linker), while a local class is, by definition, not visible outside the function, i.e., it has no linkage. It is simply impossible to have a "visible" entity as a member of an "invisible" entity. Also, there would be a bit of an ambiguity with regards to the static data member if it was allowed (assuming the linkage rules were different), because of the life-time of that static data member. Would it be like a local variable, or like a global variable, or like a local static variable? Where would you define the data member? I assume inside the function. But would that mean that that is the point of initialization? What if you define the data member within a if-statement or some other conditional block?

I think that I am glad that this is not permitted because it would be quite difficult to come to a decent solution to all this ambiguity.

Deceptikon, I'm not sure your answer was apropros to the question. It was being unable to declare a static variable inside a class defined inside a function. Honestly, I have never done that! IE, something like this I think is what (in my interpretation of the post) he meant (I may be waaay off-base...):

int functionx(void)
{
    // Local class
    class foo {
        static int s_var;
        .
        .
        .
    };
    int foo::s_var = 0;
    .
    .
    .
    return 0;
}

Personally, in 20+ years of C++ coding I have never used this construct, so I don't know if it is legal or not, and I don't have the time to dig through my C++ standards docs to see if it is allowed. I think that classes internal (and local) to a function should be ok, but the static variable part I'm not certain of.

Maybe some other expert out there can enlighten me! :-)

She is referring to a local class, not a nested class.

Ah, my mistake. I read the question too quickly.

@mike 2000 17....Thank you sir.You gave me a nice discription and my doubt is cleared now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.