Local class question

Hello everyone ,i found the following code in ibm's side

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>
using namespace std;

int x;                         // global variable
void f()                       // function definition
{
      static int y;            // static variable y can be used by
                               // local class
   //   int x;                   // auto variable x cannot be used by
                               // local class
      extern int g();          // extern function g can be used by
                               // local class

      class local              // local class
      {
            int g() { return x; }      // error, local variable x
                                       // cannot be used by g
            int h() { return y; }      // valid,static variable y
            int k() { return ::x; }    // valid, global x
            int l() { return g(); }    // valid, extern function g
      };
}

int main()
{
    
	   
}


I as you can see there is class declared locally in the function.What i want to do is to create an object of this local class inside main.Any ideas?Thanks
You can't, it's local to f()
No way. Quote from 9.8.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]

end quote
I found at http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=191 this
1
2
3
4
5
6
7
8
9
10
class A{}; //#1
void func
{
class A {};//#2
A a;//#2
}
int main()
{
 A a; //#1
}


well i can't see any point on this,do you?
That snippet just demonstrates name resolution. Read the line directly under the example in the article that you posted.
Topic archived. No new replies allowed.