Learn C++
#include "oopadvanced/nested_classes.hpp"

Nested Classes in C++

//concept

A class declared inside another (LinkedList::Node) scopes the helper to its owner — the name Node means nothing outside LinkedList, keeping namespaces clean and signaling the helper has no independent purpose. Unlike Java's inner classes, C++ nested classes get no implicit outer pointer: a Node cannot see its list's members unless handed a reference explicitly.

Access flows one way by default: the nested class can touch the outer's privates (it is a member, after all), but the outer needs no special rights to the nested class's privates either — enclosing classes see nested privates freely. Keep nested types private when they are pure implementation detail.

//how it works
1

Scope helpers to owners

struct LinkedList { struct Node { int v; Node* next; }; ... }; — Node exists only as LinkedList::Node.

2

No implicit outer link

A nested object holds no back-pointer — pass the outer reference in if the helper needs it, unlike Java inner classes.

3

Qualify from outside

Code outside the owner names the type LinkedList::Node — or keeps it entirely hidden behind the owner's interface.

4

Private by default intent

Nest privately when callers should never name the helper; public nesting suits node/iterator types users genuinely handle.

//example
#include <iostream>
 
class Stack {
struct Node {
int value;
Node* next;
};
Node* top = nullptr;
public:
void push(int v) { top = new Node{v, top}; }
int peek() const { return top->value; }
~Stack() { while (top) { Node* t = top; top = top->next; delete t; } }
};
 
int main() {
Stack s;
s.push(7);
std::cout << s.peek() << std::endl;
return 0;
}
Output
7
1Node is declared inside Stack's private region — invisible and unnameable from outside.
2push links a fresh Node atop the chain; peek reads through the top pointer.
3The destructor walks and deletes every node — 7 prints before teardown runs.
//use cases
Hiding linked-structure nodes inside their container class
Scoping iterators, builders, and handles to the type they serve
Grouping tightly-coupled helpers (parsers, states) with their owner
Passing outer context explicitly since no hidden back-pointer exists

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.