Nested Classes in C++
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.
Scope helpers to owners
struct LinkedList { struct Node { int v; Node* next; }; ... }; — Node exists only as LinkedList::Node.
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.
Qualify from outside
Code outside the owner names the type LinkedList::Node — or keeps it entirely hidden behind the owner's interface.
Private by default intent
Nest privately when callers should never name the helper; public nesting suits node/iterator types users genuinely handle.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.