Information Technology Reference
In-Depth Information
Nested Types
Types are usually declared directly inside a namespace. You can, however, also declare types
inside a class or struct declaration.
￿
Types declared inside another type declaration are called nested types . Like all type dec-
larations, nested types are templates for an instance of the type.
￿
A nested type is declared like a member of the enclosing type .
-
A nested type can be any type.
-
An enclosing type can be either a class or a struct.
For example, the following code shows class MyClass , with a nested class called MyCounter .
class MyClass // Enclosing class
{
class MyCounter // Nested class
{
...
}
...
}
Declaring a type as a nested type often makes sense if it is only meant to be used as a helper
for the enclosing type.
Don't be confused by the term nested . Nested refers to the location of the declaration —not
the location of any instances . Although a nested type's declaration is inside the enclosing type's
declaration, objects of the nested type are not necessarily enclosed in objects of the enclosing
type. Objects of the nested type—if any are created at all—are located wherever they would
have been located had they not been declared inside another type.
For example, Figure 23-7 shows objects of types MyClass and MyCounter , as outlined in the
preceding code. The figure additionally shows a field called Counter , in class MyClass , that is a
reference to an object of the nested class, which is located elsewhere in the heap.
Figure 23-7. Nesting refers to the location of the declaration, not the location of the object.
Search WWH ::




Custom Search