Can a class written in a method of another class(inner class), access the methods variables? I mean in the code below:
class A
{
void methodA( int a )
{
class B
{
void processA()
{
a++;
}
};
std::cout<<"Does this program compile?";
std::cout<<"Does the value of the variable 'a' increments?";
};
};
Is this legal?Does, the value of 'a' increments? Please suggest how.
Thanks, Pavan.
No it is not legalclass B
is a Local class to methodA()
.
class B
cannot access nonstatic "automatic" local variables of the enclosing function. But it can access the static variables from the enclosing scope.
There are several restrictions on what local classes can have access to.
Here is an reference from the C++ Standard:
9.8 Local class declarations [class.local]
[Example:
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
};
// ...
}
local* p = 0; // error: local not in scope
—end example]
2. An enclosing function has no special access to members of the local class; it obeys the usual access rules (clause 11). Member functions of a local class shall be defined within their class definition, if they are defined at all.
3. If class X is a local class a nested class Y may be declared in class X and later defined in the definition of class X or be later defined in the same scope as the definition of class X. A class nested within a local class is a local class.
4. A local class shall not have static data members.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With