Nested Type Names

Microsoft C++ supports declaration of nested types — both named and anonymous.

Syntax

qualified-type-name :

typedef-name
class-name :: qualified-type-name

complete-class-name :

qualified-class-name
:: qualified-class-name

qualified-class-name :

class-name
class-name :: qualified-class-name

In some programming situations, it makes sense to define nested types. These types are visible only to member functions of the class type in which they are defined. They can also be made visible by constructing a qualified type name using the scope-resolution operator (::).

Note   One commonly used class hierarchy that employs nested types is iostream. In the iostream header files, the definition of class ios includes a series of enumerated types, which are packaged for use only with the iostream library.

The following example defines nested classes:

class WinSystem
{
public:
    class Window
    {
    public:
        Window();         // Default constructor.
        ~Window();        // Destructor.
        int NumberOf();   // Number of objects of class.        
        int Count();      // Count number of objects of class.
    private:
        static int CCount;
    };
    class CommPort
    {
    public:
        CommPort();       // Default constructor.
        ~CommPort();      // Destructor.
        int NumberOf();   // Number of objects of class.
        int Count();      // Count number of objects of class.
    private:
        static int CCount;
    };
};

// Initialize WinSystem static members.
int WinSystem::Window::CCount = 0;
int WinSystem::CommPort::CCount = 0;

To access a name defined in a nested class, use the scope-resolution operator (::) to construct a complete class name. Use of this operator is shown in the initializations of the static members in the preceding example. To use a nested class in your program, use code such as:

WinSystem::Window Desktop;
WinSystem::Window AppWindow;

cout << "Number of active windows: " << Desktop.Count() << "\n";

Nested anonymous classes or structures can be defined as:

class Ledger
{
    class
    {
    public:
        double   PayableAmt;
        unsigned PayableDays;
    } Payables;

    class
    {
    public:
        double   RecvableAmt;
        unsigned RecvableDays;
    } Receivables;
};

An anonymous class must be an aggregate that has no member functions and no static members.

Note   Although an enumerated type can be defined inside a class declaration, the reverse is not true; class types cannot be defined inside enumeration declarations.