I recently discovered that local class cannot access Auto variables of enclosing function as they might contain invalid reference to local variable. For Example
struct Helper {
virtual int getLocal() = 0;
};
Helper* nutshell(){
int local = 123;
struct Internal : public Helper {
int i = INT16_MAX; // Unnecessary
int getLocal(){ return local; }
};
return new Internal();
};
The above code is disaster because getLocal
has invalid reference to local
. A solution for this could be making local
static or enum, But what's interesting for me is that making it a const is also a possible way.
struct Helper {
virtual int getLocal() = 0;
};
Helper* nutshell(){
const int local = 123;
struct Internal : public Helper {
int i = INT16_MAX; // Unnecessary
int getLocal(){ return local; }
};
return new Internal();
};
My question is why is that, Why local class can access const variable?
Isn't a const
qualified variable a Auto variable?