A class can be declared within the scope of another class. Such a class is called a “nested class.” Nested classes are considered to be within the scope of the enclosing class and are available for use within that scope. To refer to a nested class from a scope other than its immediate enclosing scope, you must use a fully qualified name.
The following example shows how to declare nested classes:
class BufferedIO
{
public:
enum IOError { None, Access, General };
// Declare nested class BufferedInput.
class BufferedInput
{
public:
int read();
int good() { return _inputerror == None; }
private:
IOError _inputerror;
};
// Declare nested class BufferedOutput.
class BufferedOutput
{
// Member list
};
};
BufferedIO::BufferedInput
and BufferedIO::BufferedOutput
are declared within BufferedIO
. These class names are not visible outside the scope of class BufferedIO
. However, an object of type BufferedIO
does not contain any objects of types BufferedInput
or BufferedOutput
.
Nested classes can directly use names, type names, names of static members, and enumerators only from the enclosing class. To use names of other class members, you must use pointers, references, or object names.
In the preceding BufferedIO
example, the enumeration IOError
can be accessed directly by member functions in the nested classes, BufferedIO::BufferedInput
or BufferedIO::BufferedOutput
, as shown in function good
.
Note Nested classes declare only types within class scope. They do not cause contained objects of the nested class to be created. The preceding example declares two nested classes but does not declare any objects of these class types.