Skip to Main Content
C++ In a Nutshell
book

C++ In a Nutshell

by Ray Lischner
May 2003
Intermediate to advanced content levelIntermediate to advanced
808 pages
32h 24m
English
O'Reilly Media, Inc.
Content preview from C++ In a Nutshell

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ High Performance

C++ High Performance

Viktor Sehr, Björn Andrist
Optimized C++

Optimized C++

Kurt Guntheroth
Mastering C++ Programming

Mastering C++ Programming

Jeganathan Swaminathan

Publisher Resources

ISBN: 059600298XSupplemental ContentErrata Page