Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner Class access

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.

like image 663
user844631 Avatar asked Jul 14 '11 13:07

user844631


1 Answers

No it is not legal
class 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]

  1. A class can be defined 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.

[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.

like image 196
Alok Save Avatar answered Oct 06 '22 23:10

Alok Save