views:

56

answers:

4
void foobar(){
    int local;
    static int value;
     class access{
           void foo(){
                local = 5; /* <-- Error here */
                value = 10;
           }
     }bar;    
}   
void main(){
  foobar();
}

Why doesn't access to local inside foo() compile? OTOH I can easily access and modify the static variable value.

+3  A: 

Inside a local class you cannot use/access auto variables from the enclosing scope. You can use only static variables, extern variables, types, enums and functions from the enclosing scope.

Prasoon Saurav
A: 

Make local static and then you should be able to access it

Eton B.
+1  A: 

From standard docs Sec 9.8.1,

A class can be declared within a function definition; such a class is called a local class. The name of a local class is local to its enclosing scope. The local class is in the scope of the enclosing scope, and has the same access to names outside the function as does the enclosing function. Declarations in a local class can use only type names, static variables, extern variables and functions, and enumerators from the enclosing scope.

An example from the standard docs itself,

int x;
void f()
{
static int s ;
int x;
extern int g();
struct local {
int g() { return x; } // error: x is auto
int h() { return s; } // OK
int k() { return ::x; } // OK
int l() { return g(); } // OK
};
// ...
}

Hence accessing an auto variable inside a local class is not possible. Either make your local value as static or a global one, whichever looks appropriate for your design.

liaK
A: 

Probably because you can declare object that lives out of scope of the function.

foobar() called // local variable created;
Access* a = new Access(); // save to external variable through interface
foobar() finished // local variable destroyed

...


savedA->foo(); // what local variable should it modify?
Grozz