Nested Classes


The declaration of a class may be nested within another class declaration. A class declared in this manner is referred to as a nested class. The following applies to nested classes.

Examples

Firstly, see the examples supplied in the topic of type in the subsection declaration specifiers of the chapter on declarations.

Following is a simple example demonstrating which members of a containing class may be accessed by a nested class.

int i=0;
 
struct outer                  // Declaration of outer class
{
 int i;                       // Non-static member
 static int s;                // Static member
 
 struct inner
 {
  int Value1() {return ::i;}  // Correct because refers to global i
  int Value2() {return s;}    // Correct because member s is static
  int Value3() {return i;}    // Syntax Error !! attempted to access non-static member of outer
 
  int Value4(outer* pointer_outer)  // Passed a pointer to an instance of outer
  {return pointer_outer->i;}        // Correct to do this
 };
};

The following example illustrates how nested classes are required to obey the standard access rules.

class outer                          // declare outer class
{
 static int sio;                     // private static member
 
 public:
 
  class inner                        // declare nested class
  {
   static int sii;                   // private static member

   public:
 
   int ValueI() {return sio;}        // Error !!! outer::sio is private
 
  } innerTest;                       // Note, an instance of inner contained within outer
 
 int ValueO() {return innerTest.sii;}  // Error !!! innerTest.sii is private
};

The following example illustrates how to define a method of a nested class in global scope.

struct outer                   // declare outer class
{
 struct inner                  // declare nested class
 {
  int i;
 
  int Value();                 // method of nested class declared
 };
};
 
int i=0;                       // a global i
 
int outer::inner::Value()      // definition of method of nested class
{return i;}                    // i refers to member of class inner
 
outer::inner innerTest;        // declare an instance of nested class
innerTest.i = 10;              // assign a value to i