Export (0) Print
Expand All

15 Nested Classes

Visual Studio .NET 2003

Managed classes can be nested.

Example

__gc class Outer {
   __gc class Inner {};
}; 

Constraints

  • A nested class shall not specify a class-visibility-specifier. Its accessibility is specified by the surrounding member visibility (Section 21.2) access-specifier.

    Example

    __gc class Outer {
    public:
       __gc class Inner1 {};      //    ok: Inner2 has public visibility
       private __gc class Inner2 {};   // error
    private:
       __gc class Inner3 {};      // ok: Inner3 has private visibility
    };
    
  • If a nested __gc class inherits from its parent class, it shall be defined out of line.

    Example

    // mcpp_nested_classes.cpp
    // compile with: /clr /LD
    #using <mscorlib.dll>
    
    __gc class Outer {
    public:
       __gc class Inner; // forward declaration
       int i;
        Inner *pInner;
    };
    __gc class Outer::Inner : public Outer {
       void f() { System::Console::WriteLine(i); }
    };
    
  • A nested class shall specify the __value, __gc, or __nogc class-key modifier.

    Example

    // mcpp_nested_classes2.cpp
    // compile with: /clr /LD
    #using <mscorlib.dll>
    __gc class Outer {
    public:
       // class Inner1 {};   // error
       __gc class Inner2 {};     // ok
       __nogc class Inner3 {};   // ok
       __value class Inner4 {};  // ok
    };
    
  • A nested class or struct has access to the private members of its enclosing classes.

    Example

    // mcpp_nested_classes3.cpp
    // compile with: /clr /LD
    #using <mscorlib.dll>
    
    class C {
    private: 
       static int i;
    public:
       class inner {
       public: 
          int f() {
             return C::i;
          }
       };
    };
    

This constraint does not conform to the current C++ ISO Standard but it conforms to the next version of the Standard. This change does not affect code that conforms to the current standard. For more information, see Reference C.

Show:
© 2015 Microsoft