Nested Types

You can declare and define types within a class definition. Accessing these nested types is similar to using types declared within a namespace; the class name serves as the namespace name.

Tip

Java programmers have several different kinds of nested classes to choose from, but C++ has only one. A C++ nested class is like a static member class in Java. You can construct the other forms of nested classes by adding the appropriate declarations and support code. For example:

class outer {
public:
  friend inner;   // Implicit in Java
  class inner {
  friend outer; // Implicit in Java
  public:
    // Inner member class keeps track of outer instance.
    inner(outer& out) : out_(out) {}
    int get(  ) const { return out_.x(  ); }
  private:
    outer& out_;
  }
  int x(  );
  int y(  ) { inner i(*this); return i.get(  ); }
};

Nested types obey access specifiers, so private types are usable only by the class and its friends; protected types are usable by the class, derived classes, and friends. Public types are usable anywhere. To use a nested type outside the containing class and derived classes, it must be qualified with the class name.

Nested enumerations add every enumerator to the class scope:

class Graphics {
public:
  enum color { black, red, green, yellow, blue, magenta, cyan, white };
  color pixel(int row, int col) const;
  ...
};
Graphics::color background = Graphics::white;

A typedef declaration can also be nested in a class. This technique is often used for traits (see Chapter 8):

template<typename T, std::size_t ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.