Composite
What you will learn on this page
Section titled “What you will learn on this page”- What the Composite pattern is for: a part-whole tree, where a group can contain single items and other groups, and most code should not care which it has.
- How to give a leaf and a group one interface, so that one call works on a single file or a whole folder.
- How to own a tree in modern C++: each folder owns its children
through
std::vector<std::unique_ptr<Node>>, and each child points back to its parent without owning it. - How to keep the tree a tree: refusing a folder inside itself, and leaving a refused node with its caller.
- When a plain value tree, or a
std::variant, is the simpler choice.
The problem
Section titled “The problem”A file-sync app shows the user’s files as a tree before uploading them. The tree lives in memory; reading the real disk is a separate job.
- FR-1 A folder holds files and other folders, in the order they were added.
- FR-2 List the whole tree, indented; count the files in any folder, at any depth; and show the full path of any file or folder.
- FR-3 Move a file, or a folder with everything in it, to another folder.
- FR-4 A folder must never end up inside itself, directly or through one of its own folders.
- C-1 (constraint) Names are not empty, do not contain
/, and are unique within a folder.
More kinds of entry are expected later, such as shortcuts to other folders.
The straightforward solution
Section titled “The straightforward solution”A folder is a struct with two lists, one for files and one for folders:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A file is plain data: a name and a size. std::uint64_t is an unsigned// 64-bit whole number, big enough for any real file size. `= 0` gives// bytes a starting value, so a File made without a size has 0 bytes.struct File { std::string name; std::uint64_t bytes = 0;};
// A folder keeps two separate lists: one for files and one for folders.// Both hold their elements by value, so a Folder owns everything inside// it, and copying a Folder copies the whole subtree. A std::vector of// Folder inside Folder itself is allowed (since C++17) even though// Folder is not finished yet at that line; it is what lets folders nest.// Because the two kinds live in different lists, the folder cannot// remember whether a file or a folder was added first.struct Folder { std::string name; std::vector<File> files; std::vector<Folder> folders;};
// How many files are inside `folder`, at every depth. Folders themselves// are not counted.std::size_t file_count(const Folder& folder);// The folder as indented text, one line per entry, two spaces per level// of depth. `int depth = 0` is a default argument: a caller can write// listing(home) and the top folder gets depth 0.std::string listing(const Folder& folder, int depth = 0);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Counts the files in `folder` and in every folder below it. It is// recursive: it calls itself on each sub-folder, and the calls stop at a// folder that has no sub-folders. The two kinds are handled differently:// files are counted from their list, folders are asked through a loop.std::size_t file_count(const Folder& folder) { std::size_t count = folder.files.size(); // the files directly in this folder for (const Folder& sub : folder.folders) { count += file_count(sub); // plus every file inside each sub-folder } return count;}
// Builds the listing as text: this folder's line ("name/"), then one line// per file, then each sub-folder's whole listing, one level deeper.std::string listing(const Folder& folder, int depth) { // std::string(n, ' ') is a string of n spaces: two per level of depth. // static_cast turns the int depth into the unsigned size type that the // string constructor expects (depth is never negative here). const std::string indent(static_cast<std::size_t>(depth) * 2, ' '); std::string out = indent + folder.name + "/\n"; // Files are written first, then folders, whatever order they were // added in: the two lists cannot be interleaved. for (const File& file : folder.files) { // every function: one loop per kind // A file's line is two spaces deeper than its folder's line. // std::to_string turns the byte count into text. out += indent + " " + file.name + " (" + std::to_string(file.bytes) + " bytes)\n"; } for (const Folder& sub : folder.folders) { out += listing(sub, depth + 1); // the sub-folder lists itself, one level deeper } return out;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The braces fill the struct's members in order: name "home", an// empty files list, and an empty folders list.before::Folder home{"home", {}, {}};// A folder "docs" holding one file, report.txt of 2048 bytes. The// inner {{"report.txt", 2048}} is a list of one File. push_back// stores the new folder, by value, at the end of home.folders.home.folders.push_back({"docs", {{"report.txt", 2048}}, {}}); // added firsthome.files.push_back({"notes.txt", 120}); // added second, but listed firststd::cout << "before:\n" << before::listing(home);std::cout << "before, files: " << before::file_count(home) << "\n";This is a reasonable design, and for some programs it is the right one (see When not to use it). For this app, it has problems:
- Every function has a loop per kind.
file_counthandles files, then folders; so doeslisting; so will every function written later. A third kind, such as a shortcut, means a thirdvectorinFolderand a third loop in every function. - The order is lost (FR-1). Files are always listed before folders, whatever order the user added them in, because they are in different lists.
- “A file or a folder” has no type. Moving an entry (FR-3) needs one function for files and another for folders, and so does anything else that takes “an entry”.
- There is no way up. A path (FR-2) needs each entry’s parent, and a
value struct cannot safely point at its parent: the parent is an
element of a
std::vector, which moves its elements when it grows, so a stored pointer would dangle.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) records// a failure, showing both values, if they are not equal. Both come from// the site's small test header, lld_test.hpp.// This test: home holds a.txt directly and docs holds b.txt, so the count// is 2. It passes; it is here to show that file_count needs one way of// counting for files and another for folders.LLD_TEST(before_every_function_needs_a_loop_per_kind) { before::Folder home{"home", {{"a.txt", 1}}, {}}; home.folders.push_back({"docs", {{"b.txt", 2}}, {}}); // std::size_t{2} makes the expected value the same type as the result. LLD_CHECK_EQ(before::file_count(home), std::size_t{2});}
// A folder added before a file is still listed after it.// The expected text pins down the flaw: aaa/ was added first, yet the// listing shows zzz.txt first, because files are always written before// folders. ("\n" ends each line.)LLD_TEST(before_the_order_of_entries_is_lost) { before::Folder home{"home", {}, {}}; home.folders.push_back({"aaa", {}, {}}); home.files.push_back({"zzz.txt", 1}); LLD_CHECK_EQ(before::listing(home), std::string{"home/\n zzz.txt (1 bytes)\n aaa/\n"});}Step 1: sort the data and the functions
Section titled “Step 1: sort the data and the functions”Ask, for each piece of data and each job, which kinds of entry it applies to:
| Data or job | Applies to | Where it goes |
|---|---|---|
| a name | every entry | the common base, Node |
| the folder it is in | every entry | Node, as a pointer that observes the parent |
| its full path | every entry, the same way | Node, a non-virtual function that follows the parents |
| how many files it contains | every entry, differently | Node, a virtual function: a file answers 1; a folder adds up its children |
| one line per entry in a listing | every entry, differently | Node, a virtual function |
| a file’s size in bytes | files only | File |
| the children, in order | folders only | Folder, which owns them |
| add, remove, and find a child | folders only | Folder |
The rows that apply to every entry become the shared interface. Some of them are the same for every kind (name, path), so they are written once in the base. Others are answered differently by each kind (file count, listing), so they are virtual. The rows that apply to one kind stay in that kind’s class.
The pattern
Section titled “The pattern”Composite arranges objects in a tree of parts and wholes, and gives single objects and groups of objects the same interface. Code that uses the tree calls the same function on a single item or a whole group; a group answers by calling the same function on each of its children.
It has four participants:
- The component: the interface every node has. Here,
Node. - The leaf: a node with no children. Here,
File. - The composite: a node that holds other nodes, leaves and
composites alike. Here,
Folder. - The client: code that uses nodes through the component’s
interface. Here,
mainand the tests.
Text description of the diagram
A class diagram. Node is an abstract class holding a name and a pointer to its parent Folder. It has name, parent, and path functions, and two pure virtual functions: file_count, and list, which appends lines to a string at a given depth. File derives from Node and holds a size in bytes. Folder derives from Node and holds a vector of unique pointers to Node; it has add, which takes a unique pointer by rvalue reference and returns a Node reference, remove, which returns a unique pointer, and find, which returns a Node pointer. A filled-diamond composition line shows that a Folder owns zero or more Nodes, through children_. A plain arrow from Node to Folder shows that each node observes, without owning, the folder it is in, through parent_.
Diagram source (Mermaid)
classDiagram
class Node {
<<abstract>>
-string name_
-Folder* parent_
+name() string
+parent() const Folder*
+path() string
+file_count() size_t*
+list(string& out, int depth) void*
}
class File {
-uint64_t bytes_
+bytes() uint64_t
}
class Folder {
-vector~unique_ptr~Node~~ children_
+add(unique_ptr~Node~&&) Node&
+remove(name) unique_ptr~Node~
+find(name) Node*
}
Node <|-- File
Node <|-- Folder
Folder *-- "0..*" Node : children_ (owns)
Node --> Folder : parent_ (observes)The diagram has a loop in it, and the loop is the point: a Folder is a
Node, and it holds Nodes. That is what lets a folder hold folders,
to any depth, without a separate list for each kind.
A tree built from these classes, as main builds it, looks like this:
Text description of the diagram
An object diagram of the tree in main. A unique pointer in main owns the folder home. Home owns, in order, the folder docs, the file notes.txt, and the folder photos. Docs owns the file report.txt and the folder drafts. Drafts owns the file idea.txt. Photos owns the file cat.jpg. Every one of those is a solid arrow: one owner per node. One dashed arrow, from idea.txt back to drafts, shows a parent pointer; every node except home has one, pointing at the folder that owns it, and they are left out of the drawing to keep it readable.
Diagram source (Mermaid)
flowchart TB
M(["main: unique_ptr"]) --> H["Folder home"]
H --> D["Folder docs"]
H --> N["File notes.txt"]
H --> P["Folder photos"]
D --> R["File report.txt"]
D --> Dr["Folder drafts"]
Dr --> I["File idea.txt"]
P --> C["File cat.jpg"]
I -.->|parent_| DrThe C++ implementation
Section titled “The C++ implementation”The component: Node
Section titled “The component: Node”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The component: what files and folders have in common. Nodes are held// through std::unique_ptr and never copied or moved, because each// folder's children point back at it.// Every node has a name and a parent, so Node stores them and writes// name(), parent(), and path() once for both kinds. The two jobs whose// answer depends on the kind (file_count and list) are pure virtual:// `= 0` means Node has no body for them, so Node is abstract (no plain// Node can be made) and File and Folder must each supply their own.class Node {public: // A virtual destructor, so that destroying a File or Folder through a // std::unique_ptr<Node> runs the right destructor for its real kind. virtual ~Node() = default; // `= delete` forbids copying. Declaring the copy operations also stops // the compiler from writing move operations, so a Node cannot be moved // either: a node stays at one address for its whole life. Node(const Node&) = delete; Node& operator=(const Node&) = delete;
const std::string& name() const { return name_; } const Folder* parent() const { return parent_; } // null for a root or a removed node std::string path() const; // "home/docs/report.txt"
// How many files this node holds: 1 for a file, the total below it for // a folder. Each kind gives its own answer. virtual std::size_t file_count() const = 0; // Appends this node's lines to `out`, indented by `depth` levels. A // folder appends its own line and then its children's. virtual void list(std::string& out, int depth) const = 0; // one line per node
protected: // protected: only File and Folder can call it, so a Node is always // made as one of them. explicit stops a plain string from turning into // a Node by accident. explicit Node(std::string name); // throws for an empty name or one containing '/'
private: // `friend` gives Folder access to these private members. It is how // Folder::add and Folder::remove set and clear a child's parent_, // while no other code, not even a future derived class, can. friend class Folder; // only a folder sets or clears its children's parent std::string name_; // A raw pointer that observes and never owns: the folder owns this // node, not the other way round. `= nullptr` means "no parent yet". Folder* parent_ = nullptr; // observer: the folder that owns this node};- Shared data lives in the base. Every node has a name and a
parent, so
Nodeholds them, andname(),parent(), andpath()are written once.Nodeis still abstract: its two virtual functions are pure. - The constructor checks the name (C-1) and is
protected, so aNodeis only ever made as aFileor aFolder. - Nodes cannot be copied or moved. Copying is deleted, which also
stops the compiler from generating move operations. This is
deliberate. Each child’s
parent_holds its folder’s address; a moved or copied folder would be at a new address, and its children would still point at the old one. Nodes are only ever handled throughstd::unique_ptr, which moves the pointer and leaves the node where it is. - Only a folder can change a node’s parent.
parent_is private, andFolderis afriendofNode. Aprotectedsetter would let any derived class, including a future one, set a parent without adding the node to a folder, and the two facts could disagree.
path() follows the parent pointers up to the root:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The node's full path, such as "home/docs/drafts/idea.txt". It starts// with this node's own name and climbs the parent pointers to the root,// putting each folder's name and a "/" in front. The walk ends at the// node whose parent_ is null: the root, or a node that has been removed.// A node with no parent therefore has its bare name as its path.std::string Node::path() const { std::string out = name_; // The loop variable starts at this node's parent and steps one folder // up each time round (folder = folder->parent_), until there is none. for (const Folder* folder = parent_; folder != nullptr; folder = folder->parent_) { out = folder->name() + "/" + out; // prepend: the parent's name goes first } return out;}The leaf: File
Section titled “The leaf: File”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A leaf: it has no children.// `final` means no class can derive from File. `public Node` makes every// File usable wherever a Node is expected.class File final : public Node {public: // The part after `:` runs before the body: it hands the name to the // Node constructor (std::move passes the string on without copying // it) and stores the size. Node's constructor throws // std::invalid_argument for a bad name, so a File with one is never made. File(std::string name, std::uint64_t bytes) : Node{std::move(name)}, bytes_{bytes} {} std::uint64_t bytes() const { return bytes_; }
// `override` asks the compiler to check that this really replaces a // virtual function of Node. A file holds exactly one file: itself. std::size_t file_count() const override { return 1; } // Appends one line: the name and size, indented two spaces per level. void list(std::string& out, int depth) const override;
private: std::uint64_t bytes_;};A file’s answers are simple: it contains one file, itself, and it lists as one line.
The composite: Folder
Section titled “The composite: Folder”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The composite: a node that owns other nodes, files and folders alike.// It is itself a Node, so a folder can sit inside another folder, and// code that works on a Node works on a whole folder just as on one file.class Folder final : public Node {public: explicit Folder(std::string name) : Node{std::move(name)} {}
// Make a new file or folder inside this one and return a reference to // it, so calls can be chained. The reference stays valid while the // node exists, even if it is later moved to another folder. Both throw // std::invalid_argument, and then nothing is added: for a bad name the // Node constructor refuses it, for a duplicate one add refuses it. File& add_file(std::string name, std::uint64_t bytes); Folder& add_folder(std::string name);
// Takes a node made elsewhere, or removed from another folder. // Throws std::invalid_argument, and leaves the node with the caller, // if it is null, its name is already used here, or it is this folder // or a folder that contains this one. // The parameter is an rvalue reference (`&&`), not a by-value // std::unique_ptr: nothing is moved out of the caller's pointer until // add itself does it, after every check has passed. On success the // caller's pointer is left empty, and add returns the added node. Node& add(std::unique_ptr<Node>&& child);
// Hands the node back to the caller, with no parent; null if absent. // The caller then owns it: dropping the pointer destroys the node and // everything in it, and passing it to add puts it somewhere else. std::unique_ptr<Node> remove(std::string_view name);
// Look up a direct child by name (not grandchildren). Two versions: // the second is used on a const Folder and gives back a const Node*. // std::string_view lets a caller pass a string literal or a // std::string without making a copy. Node* find(std::string_view name); // observer; null if absent const Node* find(std::string_view name) const;
std::size_t file_count() const override; void list(std::string& out, int depth) const override;
private: // One list for both kinds. Each std::unique_ptr<Node> owns one child, // which may be a File or a Folder; destroying the folder destroys them // all. Because there is one list, the order of adding is kept. std::vector<std::unique_ptr<Node>> children_; // in the order they were added};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A folder's file count is the sum of its children's counts. It does not// ask what kind each child is: the virtual call goes to File::file_count// (which answers 1) or to Folder::file_count (which repeats this loop one// level down). The recursion ends at files, which answer 1, and at// empty folders, which answer 0.std::size_t Folder::file_count() const { std::size_t count = 0; // `const auto& child` is a reference to each std::unique_ptr in the // list, so nothing is copied; `child->` reaches the node it owns. for (const auto& child : children_) { count += child->file_count(); // a file or a whole folder: the same call } return count;}
// A folder lists itself as "name/" at its own depth, then asks each child,// in the order they were added, to list itself one level deeper. A child// folder does the same, so the indentation grows by two spaces per level.void Folder::list(std::string& out, int depth) const { // std::string(n, ' ') is n spaces; static_cast turns the int depth into // the unsigned size type that this constructor takes. out += std::string(static_cast<std::size_t>(depth) * 2, ' ') + name() + "/\n"; for (const auto& child : children_) { child->list(out, depth + 1); // the same call for a file or a folder }}How this code works: Folder::file_count and Folder::list on the tree in main
Take the tree that main builds, before anything is moved:
home/ docs/ report.txt drafts/ idea.txt notes.txt photos/ cat.jpghome->file_count() asks each of its three children in turn and adds up
the answers. Each child decides for itself how to answer:
| Call | Asks | Answer |
|---|---|---|
report.txt |
nobody: it is a file | 1 |
idea.txt |
nobody: it is a file | 1 |
drafts |
idea.txt |
1 |
docs |
report.txt, drafts |
1 + 1 = 2 |
notes.txt |
nobody: it is a file | 1 |
cat.jpg |
nobody: it is a file | 1 |
photos |
cat.jpg |
1 |
home |
docs, notes.txt, photos |
2 + 1 + 1 = 4 |
The rows are in the order the answers are finished: a folder’s answer
is ready only after all of its children have answered, so home, the
first to be asked, is the last to answer. That 4 is the files: 4 line
in the output.
list follows the same shape, but it writes on the way down. Each
folder appends its own line first, then asks each child with
depth + 1. So home writes home/ at depth 0, docs writes docs/
at depth 1 (two spaces), report.txt writes its line at depth 2 (four
spaces), and so on. Because each folder writes its own line before its
children’s, a folder always appears just above its contents, and the
children come out in the order they were added.
Neither function contains an if about the kind of node. The choice
between “I am a file” and “I am a folder” is made by the virtual call
child->file_count(), which runs the version belonging to the child’s
real class.
This is the heart of the pattern. file_count and list call the
same function on each child, without asking whether the child is a
file or a folder. A file answers for itself; a folder answers by asking
its own children. The recursion stops at the leaves.
add_file and add_folder create a child in place and return a
reference to it, so a tree can be built in a few lines, as main does.
Both go through add, so the checks are in one place.
Adding and removing: keeping it a tree
Section titled “Adding and removing: keeping it a tree”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Puts `child` into this folder, after three checks. Each failed check// throws std::invalid_argument before anything has changed, so a refused// child is still owned by the caller's pointer and the tree is untouched.Node& Folder::add(std::unique_ptr<Node>&& child) { // An empty std::unique_ptr converts to false: there is no node to add. if (!child) { throw std::invalid_argument{"cannot add an empty node"}; } // Names must be unique among a folder's direct children. if (find(child->name()) != nullptr) { throw std::invalid_argument{name() + " already has " + child->name()}; } // The cycle check. Walk up from this folder to the root: this folder, // its parent, its parent's parent, and so on. If one of them is the // node being added, then that node is this folder or contains it, and // adding it would put a folder inside itself. child.get() is the raw // address of the node, without giving up ownership. for (const Folder* folder = this; folder != nullptr; folder = folder->parent_) { if (folder == child.get()) { throw std::invalid_argument{"cannot put " + child->name() + " inside itself or a folder it contains"}; } } // Every check has passed: only now take ownership. child->parent_ = this; // the child now knows its folder children_.push_back(std::move(child)); // the folder now owns it; child is left empty // children_.back() is the pointer just stored; `*` gives the node it // owns. (`child` cannot be used here: it was emptied by the move.) return *children_.back();}
// Takes the child called `name` out of this folder and gives its// ownership to the caller. Returns an empty pointer if there is no such// child, and then changes nothing.std::unique_ptr<Node> Folder::remove(std::string_view name) { // std::find_if walks the list and stops at the first element for which // the lambda says true. [name] copies the string_view into the lambda: // only a pointer and a length, not the characters. The result is an iterator: // a position in the vector, or children_.end() if nothing matched. const auto it = std::find_if(children_.begin(), children_.end(), [name](const auto& child) { return child->name() == name; }); if (it == children_.end()) { return nullptr; // not found: an empty std::unique_ptr } // *it is the std::unique_ptr in the vector. Moving from it hands the // node to `removed` and leaves an empty pointer in the vector... std::unique_ptr<Node> removed = std::move(*it); // ...which erase then takes out, closing the gap. The later children // keep their order. `it` is no longer valid after this line. children_.erase(it); removed->parent_ = nullptr; // it is in no folder now return removed;}How this code works: Folder::add and Folder::remove, traced through main
add in four steps.
- Is there a node? An empty pointer is refused.
- Is the name free here?
findlooks only at this folder’s own children. - Would it make a loop? Start at
thisand climb the parent pointers to the root. If any folder on the way up is the node being added, refuse. - Take it. Set the child’s parent, move the pointer into
children_, and return the node.
Steps 1 to 3 only read; each one that fails throws before anything has changed. Step 4 is the only one that changes anything, and it starts only after every check has passed.
remove, in order. Find the child by name (or return null),
move its std::unique_ptr out of the vector into removed, erase the
now-empty slot, clear the parent, and hand removed to the caller.
Trace 1: moving drafts up to home, from
home->add(docs.remove("drafts")).
docs.remove("drafts"): the children ofdocsarereport.txt,drafts.find_ifstops atdrafts. After the move and the erase,docshas onlyreport.txt, anddraftshas no parent.home->add(...): the pointer is not empty;homehasdocs,notes.txt, andphotos, so the namedraftsis free; the climb visits onlyhome(its parent is null), which is notdrafts. All checks pass:draftsgetshomeas its parent and goes to the end of the list.idea.path()now climbsdrafts, thenhome:home/drafts/idea.txt.
Trace 2: the refused cycle, from archive.add(std::move(taken)).
By then docs has been removed from home (so its parent is null) and
archive has been made inside docs.
| Step | What it looks at | Result |
|---|---|---|
| empty? | taken owns docs |
not empty: go on |
| name free? | archive has no children |
free: go on |
| climb, 1st | folder is archive; is it docs? |
no: go up |
| climb, 2nd | folder is docs; is it docs? |
yes: throw |
The throw happens before the two lines of step 4, so taken was never
moved from and still owns docs. That is why main can add it back to
home on the next line.
add is where the tree’s rules are kept:
- The cycle check (FR-4). A folder must not be added to itself, or
to any folder inside it.
addwalks up fromthisthrough the parents; if it meets the node being added, the node containsthis, and adding it would make a loop that no one could ever destroy. The walk costs one step per level of depth. std::unique_ptr<Node>&&, not a by-value parameter. The usual advice is to take astd::unique_ptrby value when a function takes ownership. Here that would be a trap. With a by-value parameter, the node is moved out of the caller’s pointer beforeaddruns; ifaddthen refuses it, the parameter is destroyed, and the node with it. In the cycle case, that node contains the folderaddwas called on. In a scratch program (not kept with the examples) with a by-valueadd, a refused cycle destroyed the folder, and the next use of a reference to it was reported by AddressSanitizer as heap-use-after-free, with both GCC and Clang. A refused duplicate name would lose the caller’s node in the same way, without the crash. Taking an rvalue reference and moving from it only after every check passes means a refused node is still the caller’s.- Using
takenafterstd::move(taken).maindoes this on purpose, and it is usually a mistake, so it needs a word.std::movemoves nothing: it only lets the pointer bind to the&¶meter. The pointer is emptied only whenadditself moves from it, whichaddpromises to do only on success. Because that is a promise of this one function, not a rule of the language, the comment onaddintree.hppstates it; tools such as clang-tidy’s use-after-move check may still warn about the caller. removehands ownership back. It returns thestd::unique_ptr<Node>, with its parent cleared. The caller can drop it (the node and everything in it are destroyed) or add it elsewhere, which is how a move (FR-3) works. Removing a missing name returns null.
class Node
the component: abstract; not copyable or movable
Data members
std::string name_;checked: not empty, no '/'Folder* parent_;observer: the folder that owns this node; null for a root
Member functions
const std::string& name() const;const Folder* parent() const;std::string path() const;follows the parents to the rootvirtual std::size_t file_count() const = 0;virtual void list(std::string& out, int depth) const = 0;
class File final
the leaf
Data members
std::uint64_t bytes_;
Member functions
File(std::string name, std::uint64_t bytes);std::uint64_t bytes() const;
class Folder final
the composite: owns its children
Data members
std::vector<std::unique_ptr<Node>> children_;in the order added
Member functions
File& add_file(std::string name, std::uint64_t bytes);Folder& add_folder(std::string name);Node& add(std::unique_ptr<Node>&& child);throws, leaving child with the callerstd::unique_ptr<Node> remove(std::string_view name);null if absentNode* find(std::string_view name);observer; null if absent
The outline leaves out the constructors of Node and Folder, the
const overload of find, and the overrides of file_count and
list.
Ownership and lifetime
Section titled “Ownership and lifetime”- One owner per node.
mainowns the root through astd::unique_ptr<Folder>; every folder owns its children throughstd::unique_ptr<Node>. Destroying the root destroys the whole tree, with no leaks. - Parent pointers observe. A child’s
parent_never owns. It stays valid because a child attached to a folder cannot outlive it: the folder destroys its children in its own destructor, andremoveclears the pointer before handing the child out. - Ownership cannot form a cycle. With one owner per node, a loop of
std::unique_ptrs would own itself, and nothing outside could ever destroy it. That is why FR-4 is not only a business rule: a cycle would leak every node in the loop, and any code that walked the loop, such asfile_count, would recurse until the stack ran out. - References survive moves of ownership.
add_folderandfindreturn a reference or pointer to the node. It stays valid while the node exists, even if the node is removed and added elsewhere, because moving astd::unique_ptrdoes not move the node.mainrelies on this:ideastill names the same file after its folder has moved, andidea.path()gives the new path. - References dangle when the node is destroyed, for example when a
removed node’s
std::unique_ptris dropped. Hold them only as long as you know the node is in the tree. - Deep trees recurse.
file_count,list, and destruction each go a few function calls deeper per level (destroying a folder runs the destructors of itsstd::vectorand eachstd::unique_ptr, which destroy the next folder). A file tree is a few dozen levels deep at most, which is no problem; a tree tens of thousands of levels deep could run out of stack, and would need loops with an explicit stack instead, including a hand-written destructor that takes the children out before they are destroyed. - Threads: several threads may read the same tree at once, but nothing here locks. Any thread that adds, removes, or moves must have the tree to itself.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// main owns the root folder through a std::unique_ptr; the root owns// everything else. `home->` calls a member through the pointer.auto home = std::make_unique<Folder>("home");// add_folder and add_file create the child inside its folder and hand// back a reference to it. The folder owns the child; `docs`, `drafts`,// and `idea` are only names for nodes that live inside the tree.Folder& docs = home->add_folder("docs");docs.add_file("report.txt", 2048);Folder& drafts = docs.add_folder("drafts");const File& idea = drafts.add_file("idea.txt", 30);home->add_file("notes.txt", 120);// Calls can be chained: add_folder returns the new folder, and// add_file is then called on it.home->add_folder("photos").add_file("cat.jpg", 500000);
// list appends to a string the caller provides, starting at depth 0.std::string out;home->list(out, 0);std::cout << "tree:\n" << out;std::cout << "files: " << home->file_count() << "\n";std::cout << "path: " << idea.path() << "\n";
// Move drafts up to home: the folder and everything in it.// docs.remove hands back the std::unique_ptr that owned drafts, and// home->add takes it over. Only the pointer moves: the drafts folder// and idea.txt stay where they are in memory, so `idea` and `drafts`// still refer to them, and idea.path() now reports the new path.home->add(docs.remove("drafts"));std::cout << "moved: " << idea.path() << "\n";
// Try to put docs inside a folder of its own.// `taken` now owns docs. The reference `docs` is still good, because// the folder was not destroyed, only handed to a new owner.std::unique_ptr<Node> taken = home->remove("docs");Folder& archive = docs.add_folder("archive");try { // std::move(taken) moves nothing by itself; it only lets `taken` // bind to add's `&&` parameter. add finds that docs contains // archive, throws std::invalid_argument, and never moves from it. archive.add(std::move(taken));} catch (const std::invalid_argument& error) { // error.what() is the message the throw was given. std::cout << "refused: " << error.what() << "\n";}// Using `taken` after std::move(taken) is normally a mistake. It is// safe here only because add promises to move from it on success// alone, and that add threw.home->add(std::move(taken)); // the failed add left it with us
out.clear(); // empty the string, so the second listing starts freshhome->list(out, 0);std::cout << "tree:\n" << out;How this code works: What main does to the tree, step by step
The children of home and docs, in order, after each step:
| Step | home holds |
docs holds |
|---|---|---|
| tree built | docs, notes.txt, photos |
report.txt, drafts |
home->add(docs.remove("drafts")) |
docs, notes.txt, photos, drafts |
report.txt |
taken = home->remove("docs") |
notes.txt, photos, drafts |
report.txt |
docs.add_folder("archive") |
notes.txt, photos, drafts |
report.txt, archive |
archive.add(std::move(taken)) throws |
unchanged | unchanged |
home->add(std::move(taken)) |
notes.txt, photos, drafts, docs |
report.txt, archive |
The last row is the final listing in the output. Three things to notice:
- Who owns
docschanges twice (home, thentaken, thenhomeagain), but the folder itself never moves in memory. That is why the referencedocsis still usable afterremove: it names the same object, whichtakennow owns. - A move goes to the end.
addalways appends, sodraftsand thendocscome after the entries that stayed put. - The refused add changed nothing.
takenstill ownsdocs, andarchiveis still empty. Usingtakenafterstd::move(taken)is safe here only becauseaddthrew before it moved from the pointer.
before:home/ notes.txt (120 bytes) docs/ report.txt (2048 bytes)before, files: 2tree:home/ docs/ report.txt (2048 bytes) drafts/ idea.txt (30 bytes) notes.txt (120 bytes) photos/ cat.jpg (500000 bytes)files: 4path: home/docs/drafts/idea.txtmoved: home/drafts/idea.txtrefused: cannot put docs inside itself or a folder it containstree:home/ notes.txt (120 bytes) photos/ cat.jpg (500000 bytes) drafts/ idea.txt (30 bytes) docs/ report.txt (2048 bytes) archive/Read the output against the requirements:
- The first tree lists
docsbeforenotes.txt, because it was added first (FR-1). The before-version listednotes.txtfirst, althoughdocswas added first, because its files and folders are in different lists. files: 4counts the files at every depth with one call on the root (FR-2); the same call works on any folder, or on a single file.- The path of
idea.txtchanges fromhome/docs/drafts/idea.txttohome/drafts/idea.txtwhendraftsis moved (FR-2, FR-3). The file was not touched: its folder’s parent changed. - Putting
docsinside its ownarchivefolder is refused (FR-4), and becauseadddid not take it,takenstill ownsdocs, which is put back at the end ofhome, witharchiveinside it.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test; LLD_CHECK(condition) fails if the// condition is false; LLD_CHECK_EQ(actual, expected) fails if the two// differ; LLD_CHECK_THROWS(expression, type) fails unless the expression// throws that type of exception. They come from lld_test.hpp.//// static_assert is checked by the compiler, not when the tests run: if// the condition is false, the file does not compile. These two prove that// Node is abstract (it has pure virtual functions, so no plain Node can// be made) and that a Folder can be neither copied nor moved.static_assert(std::is_abstract_v<Node>);static_assert(!std::is_copy_constructible_v<Folder> && !std::is_move_constructible_v<Folder>);
// One file directly in home and one inside docs. The same call,// file_count, is made on the root folder, on a sub-folder, and on a file.// find returns a Node*, so `->` calls through it without knowing the kind.LLD_TEST(files_and_folders_are_counted_the_same_way) { Folder home{"home"}; home.add_file("a.txt", 1); home.add_folder("docs").add_file("b.txt", 2); LLD_CHECK_EQ(home.file_count(), std::size_t{2}); LLD_CHECK_EQ(home.find("docs")->file_count(), std::size_t{1}); LLD_CHECK_EQ(home.find("a.txt")->file_count(), std::size_t{1});}
// The same case as the before-test: folder aaa is added before file// zzz.txt, and now the listing shows them in that order.LLD_TEST(the_listing_keeps_the_order_of_entries) { Folder home{"home"}; home.add_folder("aaa"); home.add_file("zzz.txt", 1); std::string out; home.list(out, 0); LLD_CHECK_EQ(out, std::string{"home/\n aaa/\n zzz.txt (1 bytes)\n"});}
// Three levels of nesting, built with chained calls. path() climbs from// idea.txt through drafts and docs to home. The root has no parent.LLD_TEST(paths_follow_the_parents) { Folder home{"home"}; const File& idea = home.add_folder("docs").add_folder("drafts").add_file("idea.txt", 3); LLD_CHECK_EQ(idea.path(), std::string{"home/docs/drafts/idea.txt"}); LLD_CHECK(home.parent() == nullptr);}
// remove hands the file back with its parent cleared, and docs no longer// counts it. Added to home, the same file now has the path// home/report.txt. Removing a name that is not there gives back null.LLD_TEST(a_removed_node_has_no_parent_and_can_be_added_elsewhere) { Folder home{"home"}; Folder& docs = home.add_folder("docs"); docs.add_file("report.txt", 10); std::unique_ptr<Node> report = docs.remove("report.txt"); LLD_CHECK(report != nullptr); LLD_CHECK(report->parent() == nullptr); LLD_CHECK_EQ(docs.file_count(), std::size_t{0}); home.add(std::move(report)); LLD_CHECK_EQ(home.find("report.txt")->path(), std::string{"home/report.txt"}); LLD_CHECK(docs.remove("missing") == nullptr);}
// docs contains drafts; the test tries to put docs inside drafts. The// std::unique_ptr<Folder> is first moved into a std::unique_ptr<Node>,// the type add takes (ownership passes; docs is left empty). The add must// throw, and afterwards as_node must still own docs, and drafts must// still hold no files. Without the rvalue-reference parameter, the refused// docs would have been destroyed, and drafts with it.LLD_TEST(a_folder_cannot_be_put_inside_itself) { auto docs = std::make_unique<Folder>("docs"); Folder& drafts = docs->add_folder("drafts"); std::unique_ptr<Node> as_node = std::move(docs); LLD_CHECK_THROWS(drafts.add(std::move(as_node)), std::invalid_argument); LLD_CHECK(as_node != nullptr); // the failed add left it with the caller LLD_CHECK_EQ(drafts.file_count(), std::size_t{0});}
// Each refused call throws std::invalid_argument: a duplicate name, an// empty name, a name with '/', and a null node (nullptr becomes an empty// std::unique_ptr). The last check shows that the duplicate a.txt was not added.LLD_TEST(names_must_be_usable_and_unique_in_a_folder) { Folder home{"home"}; home.add_file("a.txt", 1); LLD_CHECK_THROWS(home.add_file("a.txt", 2), std::invalid_argument); LLD_CHECK_THROWS(home.add_folder(""), std::invalid_argument); LLD_CHECK_THROWS(home.add_folder("a/b"), std::invalid_argument); LLD_CHECK_THROWS(home.add(nullptr), std::invalid_argument); LLD_CHECK_EQ(home.file_count(), std::size_t{1});}files_and_folders_are_counted_the_same_waycallsfile_counton a folder, a sub-folder, and a file, through the same interface.the_listing_keeps_the_order_of_entriesis the before-test’s case, now correct.a_folder_cannot_be_put_inside_itselfchecks the refusal and that the caller still owns the node afterwards.- The
static_asserts check thatNodeis abstract and that aFoldercan be neither copied nor moved.
Limits of the example
Section titled “Limits of the example”The tree is in memory only. For the real disk, C++17’s
std::filesystem already provides paths, directory iteration, and file
sizes; a tree like this one would be filled from it. Names are compared
exactly, so Notes.txt and notes.txt are different names here, which
is not true on every file system.
Safety or uniformity: where add is declared
Section titled “Safety or uniformity: where add is declared”In this design, add, remove, and find are on Folder only. Code
holding a Node& cannot add to it without first knowing it is a folder.
The other choice is to put them on Node, so that every node has them
and a File refuses at run time (by throwing). That makes the
interface completely uniform: clients never need to know which kind
they have. But it lets clients write code that can only fail, such as
adding a child to a file, and the compiler cannot catch it.
This page chooses safety: the operations that only make sense for
folders are only on folders, and the compiler rejects the rest. The
operations that make sense for every node (file_count, list,
path) are on Node. Descriptions of the pattern often lean the other
way, towards uniformity; this page prefers mistakes that the compiler
reports to mistakes that a test must find. Choose uniformity only when clients really must add children to nodes they
know nothing about.
Another form: a value tree with std::variant
Section titled “Another form: a value tree with std::variant”When the set of kinds is fixed and small, and the program owns all of them, a value tree avoids the class hierarchy, the heap allocation per node, and the virtual calls:
// Plain data, held by value: no base class and no virtual functions.struct File { std::string name; std::uint64_t bytes = 0;};// "There is a struct called Folder; its members come below." Entry needs// the name before Folder is complete.struct Folder;// An Entry holds exactly one of the listed types at a time: a File or a// Folder. It is a value, not a pointer, so no heap allocation per entry.using Entry = std::variant<File, Folder>;// One list for both kinds, so the order of adding is kept.struct Folder { std::string name; std::vector<Entry> entries; // files and folders, in order};
// Declared first, because the Folder version below calls it before its// body appears.std::size_t file_count(const Entry& entry);
// A folder's count is the sum of its entries' counts.std::size_t file_count(const Folder& folder) { std::size_t count = 0; for (const Entry& entry : folder.entries) { count += file_count(entry); // calls the Entry version } return count;}
// An entry asks which kind it holds. std::get_if<Folder> returns a pointer// to the Folder if the variant holds one, and nullptr if it holds a File.// The `if` with a declaration runs its body only for a non-null pointer.std::size_t file_count(const Entry& entry) { if (const auto* folder = std::get_if<Folder>(&entry)) { return file_count(*folder); // a folder: count what is inside it } return 1; // not a folder, so it is a file: it counts as one}This keeps the order (one list), and whole trees can be copied like
values (comparing them needs an operator== for each struct). It
compiled and ran with GCC and Clang in a scratch program.
The costs are the mirror image of Composite’s:
- A new kind changes every function that looks inside an
Entry, thoughstd::visitwith an overload for each kind makes the compiler report the ones you missed. - No parent pointers, for the reason given above: entries live in
std::vectors and move when they grow. Paths must be built on the way down instead. - Moving a folder copies or moves its values, so references into the tree are not stable.
Choose the class hierarchy when kinds will be added (by you or by others), when nodes need stable identity and parent links, or when operations differ a lot between kinds. Choose the value tree when the kinds are fixed and the tree is data.
When to use it
Section titled “When to use it”- The data is a part-whole tree: folders and files, menus and menu items, a drawing’s groups and shapes, an order’s bundles and items, an organisation’s departments and people.
- Most code should treat one item and a group the same way: “how many files”, “draw”, “total price”.
- Groups contain groups, to any depth, so a fixed number of levels will not do.
- New kinds of node are expected, and each should need only its own class.
When not to use it
Section titled “When not to use it”- The depth is fixed. An order with lines, and nothing deeper, is a
std::vector<OrderLine>. No tree is needed. - All nodes behave the same. If every node is just a name and some
children, one
struct Node { std::string name; std::vector<Node> children; }is enough. - The kinds are fixed and the tree is data. Use the value tree
with
std::variantshown above. - The structure is not a tree. If a node can have two parents, or links can form loops (a web of pages, a road network), it is a graph, and needs a different ownership plan: often one container owning all nodes, with links as ids or observer pointers.
- One heap allocation per node, and a virtual call per node per operation. For a file-sync app’s tree this is nothing; for millions of tiny nodes, measure.
- Ownership must be designed. Unique owners, observer parent pointers, and refusing cycles are all needed to make the tree safe; this page spends a whole section on them.
- Operations multiply in the base. Every operation that must work
on every node is a virtual function in
Node. Ten operations mean ten functions in every node class. When operations are added more often than kinds, the Visitor pattern moves them out of the classes. - Kind-specific work needs a cast. Code that holds a
Node&and needs aFile’s size must ask, withdynamic_cast. Some of that is normal; a lot of it means the interface is missing an operation.
Common misuse
Section titled “Common misuse”std::shared_ptrfor children “to be safe”. Shared ownership lets a node have two owners, which is not a tree, and a child holding astd::shared_ptrto its parent creates a cycle that is never freed. A tree has one owner per node:std::unique_ptr.- An owning parent pointer. The parent owns the child, so the child must not own the parent. Use a raw pointer (or reference) that observes.
- Checking kinds in the client. A loop that asks
dynamic_cast<Folder*>for every child, to decide what to do, has rebuilt the before-version. Add the operation toNodeinstead. - Forgetting the cycle check. Without it,
addcan be given an ancestor, and the tree becomes a loop that owns itself. - Making nodes copyable by default. A copied folder with the same
children’s
std::unique_ptrs cannot compile; a copied folder whose children still point at the original is a bug. If copies are needed, write a deliberate deep copy, such as aclonefunction (see Prototype), that also sets the new parents.
When the requirements change
Section titled “When the requirements change”- “Add shortcuts to folders.” A new leaf class,
Shortcut, holding an observer pointer (or a path) to its target. It answersfile_countwith 0, so it does not count its target twice, and it lists asname -> target.Folderand the existing classes do not change. - “Show sizes.” A new operation on every node: the exercise below.
- “Sort the listing by name.” A change inside
Folder::listonly, or a sorted copy of the children for display, leaving the stored order alone. - “Walk the tree without recursion”, for example to show it one page at a time. That is an iterator over the tree; see Iterator.
Exercise
Section titled “Exercise”Exercise: Add size computation safely
The app must show how many bytes each folder holds, counting everything inside it at every depth, before an upload starts.
- Add
size()to the tree. A file’s size is itsbytes(); a folder’s size is the total of everything in it; an empty folder’s size is 0. - Your function adds up numbers it did not choose. What can go wrong, and what should happen then?
- Someone suggests caching each folder’s size in a data member, so that it is not recomputed. What must then change, and is it worth it?
- Why can
size()assume that it will finish?
Show the explained answer
1. A new virtual function in Node, answered by each kind:
// In Node: pure virtual, so every kind of node must answer it.virtual std::uint64_t size() const = 0;
// In File: a file's size is its own byte count.std::uint64_t size() const override { return bytes_; }
// In Folder (declared in the class, defined in tree.cpp):// the total of its children's sizes; 0 for an empty folder.std::uint64_t Folder::size() const { std::uint64_t total = 0; for (const auto& child : children_) { const std::uint64_t part = child->size(); // a file or a whole folder // Would total + part go past the largest std::uint64_t? Asked this // way round, the test itself cannot overflow: max() - total is // never negative, because total never exceeds max(). if (part > std::numeric_limits<std::uint64_t>::max() - total) { throw std::overflow_error{"the size of " + path() + " is too large to count"}; } total += part; } return total;}For the tree in main, before drafts is moved, home->size() is
502198, docs is 2078, and photos is 500000. (This answer was compiled and run with GCC and
Clang; <limits> and <stdexcept> are needed in tree.cpp.)
2. Unsigned arithmetic wraps silently: if the total passes the
largest std::uint64_t, it starts again from 0, and the app would
report a tiny size for a huge folder. Real file sizes will not reach
that limit, but the sizes come from outside (the disk, or a server),
and a corrupt value can. The check before each += turns that into an
std::overflow_error naming the folder. A test with two files of just
over half the maximum each shows the check working.
3. Every change below a folder must reach the cache of every folder above it: adding, removing, or moving a node, and changing a file’s size if that becomes possible. With the parent pointers that is possible (walk up and mark each cache stale), but every function that changes the tree must remember to do it, and a single miss shows a wrong size with no error. For a tree of a few thousand entries, recomputing on each call is fast enough, so do not cache until a measurement says you must.
4. Because add refuses cycles (FR-4), every path down the tree
ends at a leaf or an empty folder, so the recursion stops. A
Shortcut that followed its target in size() could bring the cycle
back, which is one more reason for it to answer 0. Without that
check, a folder inside itself would make size(), file_count(), and
list() recurse until the stack ran out.
Related patterns
Section titled “Related patterns”- Visitor moves operations out of a stable set of node classes, so that new operations do not change them. It is often used with Composite when operations change more often than kinds. See Visitor.
- Iterator walks a tree without the client knowing its structure. See Iterator.
- Prototype gives the nodes a deep
clone, when copies of subtrees are needed. See Prototype. - Decorator has the same shape as a composite with exactly one child: it wraps one object and keeps its interface, to add behaviour rather than to group. See Decorator.
Summary
Section titled “Summary”- Composite gives single objects (leaves) and groups (composites) one interface, the component, so that code works on a part or a whole the same way.
- A composite answers an operation by calling the same operation on each child; the recursion ends at the leaves.
- In C++, own the tree with
std::unique_ptr: each folder owns its children in astd::vector<std::unique_ptr<Node>>, and a child’s parent pointer only observes. - Keep it a tree: refuse cycles, make nodes non-copyable and non-movable when children point at their parent, and leave a refused node with its caller by moving from it only after every check.
- When the kinds are fixed and the tree is plain data, a value tree
with
std::variantis simpler.