Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 171 Β· Object-Oriented Programming

Nested and Local Classes

Learn C++ nested classes and their access rules, private helper types like list nodes, the pimpl idiom for stable headers, and local classes defined inside functions.

Classes don't have to live at namespace scope. You can define a class inside another class, where it becomes a member type like std::vector<int>::iterator or std::map<K, V>::value_type, and you can even define a class inside a function, where nothing outside the function can see it. Both are tools for putting a type exactly where it belongs: a linked list's node type is an implementation detail of the list, and a tiny helper class used by one function shouldn't clutter the namespace.

This lesson covers nested classes and their access rules (which differ from Java's inner classes in an important way), public nested types that form part of an interface, a subtle default-argument pitfall, the pimpl idiom that uses a nested class to hide a class's private members from its header, and local classes, including how they relate to lambdas. It builds on Classes and Objects and Access Specifiers and Encapsulation.

Nested classes

A class defined inside another class is a nested class. Its full name is Outer::Inner, and it obeys the access specifier of the section it's declared in: a nested class under private: can only be used by Outer (and its friends), while one under public: is available to everyone as Outer::Inner.

The classic example is a container's node type. Users of the list never need to know nodes exist:

C++ A private Node class inside a list

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Node uses std::unique_ptr for ownership, so the whole chain is freed when the list is destroyed (see Smart Pointers: std::unique_ptr). Keeping Node private means you can later switch to a doubly linked list or a different node layout without breaking any user's code.

Access rules

Nested classes have a specific, asymmetric relationship with their enclosing class:

  • A nested class is a member of the outer class, so it can access the outer class's private members, provided it has an object to access them through. (This has been the rule since C++11.)
  • The outer class has no special access to the nested class. If Node declared private members, TodoList couldn't touch them unless Node made TodoList a friend. That's why private helper types are often plain structs with public members: the outer class's own private: section already hides them from everyone else.
  • There is no hidden outer object. Unlike a Java inner class, a C++ nested class object is completely independent: it doesn't carry a pointer to an "enclosing" Outer object. If it needs one, you pass it in explicitly, usually as a reference or pointer member.
C++ Nested class access in both directions

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The auditor sees owner_ and balance_ because it's a member of Account. If Account tried to read auditor.visits_, the compiler would reject it with "'int Account::Auditor::visits_' is private within this context".

Public nested types as part of an interface

Nested types are also how classes name the types that go with them. The standard library does this everywhere: std::vector<int>::iterator, std::string::size_type, std::map<K, V>::value_type. In your own code, a nested Options, Result or Error type keeps related names together and avoids collisions: Downloader::Options and Renderer::Options can coexist.

You can declare a nested class inside the outer class and define it later, and member functions of nested classes can be defined outside with a doubly qualified name:

C++ Nested types defined outside the class

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Notice the return type of Parser::parse in its out-of-class definition: it's written Parser::Result, because the return type comes before the compiler knows we're inside Parser. The parameter list and body come after Parser::parse, so inside them the short name Result works. A trailing return type avoids the repetition: auto Parser::parse(...) -> Result.

A nested struct's default member initializers can't be used by the enclosing class's own default arguments. This looks harmless but fails to compile:

C++
class Widget {
public:
    struct Options { int width = 100; bool visible = true; };
    explicit Widget(Options options = {});   // error with GCC: could not convert '{}' to 'Widget::Options'
};

The default member initializers of Options are only usable once Widget is complete, but the default argument is checked earlier. Fixes: define Options outside Widget (for example as WidgetOptions in the same namespace), or provide two constructors, Widget() and explicit Widget(Options), with the first delegating to the second.

The pimpl idiom

In C++, a class's private members are part of its header. Every file that includes widget.h sees them, and whenever you add or change a private member, every one of those files must be recompiled. Private members may also drag in heavy headers (<map>, a database library, platform headers) that users of the class shouldn't have to include.

The pimpl idiom ("pointer to implementation") breaks that dependency. The header declares a nested class Impl but doesn't define it, and the public class holds only a std::unique_ptr<Impl>. Everything private moves to the .cpp file. (Splitting code into headers and source files is covered in Header Files and Multiple Source Files.)

C++
// widget.h: what users include. No private details, no heavy includes.
#pragma once
#include <memory>
#include <string>

class Widget {
public:
    explicit Widget(std::string name);
    ~Widget();                                // declared here, defined in widget.cpp
    Widget(Widget&&) noexcept;                // moves too
    Widget& operator=(Widget&&) noexcept;

    void click();
    int clicks() const;

private:
    struct Impl;                              // declared, not defined
    std::unique_ptr<Impl> impl_;
};
C++
// widget.cpp: the only file that knows what Impl contains.
#include "widget.h"
#include <map>                                // heavy dependencies stay here
#include <print>

struct Widget::Impl {
    std::string name;
    int clicks = 0;
    std::map<std::string, std::string> settings;
};

Widget::Widget(std::string name) : impl_{std::make_unique<Impl>(std::move(name))} {}
Widget::~Widget() = default;                  // Impl is complete here
Widget::Widget(Widget&&) noexcept = default;
Widget& Widget::operator=(Widget&&) noexcept = default;

void Widget::click() { ++impl_->clicks; std::println("{} clicked", impl_->name); }
int Widget::clicks() const { return impl_->clicks; }

The one tricky part is the destructor. std::unique_ptr<Impl> must see the complete Impl type to delete it. If you let the compiler generate ~Widget() in the header, it's generated wherever Widget is destroyed, where Impl is incomplete, and compilation fails with an error about applying sizeof to an incomplete type. Declaring the destructor (and the move operations) in the header and defaulting them in the .cpp file, after Impl is defined, solves it.

Our editor compiles one file at a time, so this example combines both parts into one program. The structure is the same: Impl is complete before the destructor is defined.

C++ Pimpl in a single file

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

sizeof(Playlist) is just one pointer, whatever Impl contains. Pimpl gives you stable headers, faster rebuilds, and a stable binary layout for shared libraries (adding a private member doesn't change sizeof of the public class). The costs are one heap allocation per object, an extra pointer indirection on every access, and a little boilerplate. It's worth it for large classes in widely included headers and for library APIs, not for small value types. A moved-from pimpl object holds a null impl_, so calling show() on it would crash; document that, or check for it.

Local classes

A local class is defined inside a function body. Its name is visible only from the point of definition to the end of that block. Before C++11, local classes were the only way to write small throwaway function objects, and they're still the right tool when a function needs a private implementation of an interface:

C++ A local class implementing an interface

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Nothing outside make_greeter can name English, Spanish or Polite, yet the objects live on happily after the function returns: they're ordinary heap objects owned by the returned std::unique_ptr<Greeter>. Compare this with the factory in Abstract Classes and Interfaces, where the concrete classes were visible to the whole file.

Local classes have a few restrictions:

  • They can't use the function's local (automatic) variables. A member function of a local class runs at some later time, when those variables may no longer exist. Using one is an error ("use of local variable with automatic storage from containing function"). Static locals, global variables, types, enumerators and constants that aren't odr-used are fine. Pass anything else through a constructor, as Polite does with its title.
  • No static data members and no member templates (so no generic member functions).
  • All member functions must be defined inside the class body.

Lambdas are local classes in disguise

That first restriction is exactly what lambdas were invented to solve. A lambda expression creates an object of an unnamed local class, its closure type, and its capture list automatically copies or references the local variables you name into members of that class:

C++
int threshold = 10;

// What you write:
auto is_big = [threshold](int x) { return x > threshold; };

// Roughly what the compiler generates:
struct Closure {
    int threshold;                                   // the capture
    bool operator()(int x) const { return x > threshold; }
};
auto is_big2 = Closure{threshold};

So for short function objects (comparators, predicates, callbacks), write a lambda; see Lambda Expressions. Reach for a named local class when you need several member functions, a virtual interface implementation, or a type you want to refer to by name inside the function.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. class List { private: struct Node { int value; }; }; What does List::Node n{5}; in main() do?

    A nested class follows the access specifier it is declared under. A private nested type can only be named by the enclosing class and its friends.
  2. 2. A nested class Inner has a member function that receives a const Outer& o. Can it read o's private members?

    Since C++11 a nested class has access to all members of its enclosing class. The reverse is not true; Outer can't read Inner's private members.
  3. 3. How does a C++ nested class differ from a (non-static) Java inner class?

    C++ nested classes are independent types that happen to live in the outer class's scope. If an Inner needs an Outer, you pass one in explicitly.
  4. 4. In the pimpl idiom, why is ~Widget() declared in the header and defined (even as = default) in the .cpp file?

    The destructor deletes the Impl object, which requires its full definition. Defining the destructor after Impl is defined avoids the incomplete-type error.
  5. 5. A function declares int limit = 5; and then a local class whose member function returns x > limit. What happens?

    Member functions of a local class can't use the enclosing function's automatic variables. Pass the value in through a constructor, or use a lambda capture.

Summary

  • A nested class lives in its enclosing class's scope (Outer::Inner) and follows the access specifier it's declared under. Private nested classes are ideal for implementation details such as list nodes.
  • A nested class can access the outer class's private members (it's a member); the outer class has no special access to the nested class. There's no hidden link to an enclosing object.
  • Public nested types (Options, Result, iterator) name the types that belong to a class. They can be declared inside and defined outside, with members defined as Outer::Inner::f.
  • A nested struct's default member initializers can't be used in the enclosing class's default arguments; define the struct outside or add a separate constructor.
  • The pimpl idiom hides private members behind std::unique_ptr<Impl>, giving stable headers and faster builds; define the destructor and moves in the .cpp file.
  • A local class is visible only inside its function, is handy for hidden interface implementations, and can't use the function's automatic variables. Lambdas are compiler-generated local classes that capture those variables for you.

Next: Function Templates, the start of generic programming in C++.