{"slug":"cpp-oop-style","title":"cpp-oop-style","summary":"High-quality C++ OOP coding style (archibate / parallel101 lineage) that overrides sloppy AI-default C++. Use this skill WHENEVER writing, editing, refactoring, or reviewing C++ code (.cpp / .h / .hpp / .cc / .cxx), designing C++ classes, interfaces, APIs, or libraries, or when t","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-12-03T18:25:07.941603Z","repo":{"url":"https://github.com/archibate/agent-skills","stars":19,"forks":2,"license":null,"updatedAt":"2026-12-01T03:54:49Z"},"bodyHtml":"<hr>\n<h2>name: cpp-oop-style\ndescription: &gt;-\nHigh-quality C++ OOP coding style (archibate / parallel101 lineage) that\noverrides sloppy AI-default C++. Use this skill WHENEVER writing, editing,\nrefactoring, or reviewing C++ code (.cpp / .h / .hpp / .cc / .cxx), designing\nC++ classes, interfaces, APIs, or libraries, or when the user mentions C++\ndesign, OOP, design patterns, dependency injection, RAII, or \"clean / modern\nC++\". Also use it for CMake-based C++ project setup, module targets, usage\nrequirements, third-party dependency acquisition and integration, binary ABI\ncompatibility, installation, packaging, and application deployment.</h2>\n<h1>archibate C++ OOP Style</h1>\n<p>A skill that makes you write C++ the way a senior systems engineer who loves\ndesign patterns writes it — not the way an autocompleter does. When this skill\nis loaded, it <strong>overrides</strong> your default C++ instincts.</p>\n<h2>The one rule</h2>\n<blockquote>\n<p><strong>\"Abstract class, data class, or value type. Nothing else.\"</strong></p>\n</blockquote>\n<p>Every type you introduce is one of these three kinds — never the muddy middle:</p>\n<ul>\n<li><strong>Abstract class</strong> — <em>behavior only</em>. A pure-virtual interface with no data\nmembers of its own; any injected collaborators live in its concrete <code>…Impl</code>,\nnot in the interface. Always has <code>virtual ~T() = default;</code>. This is the unit of\n<em>polymorphism and dependency injection</em>.</li>\n<li><strong>Data class</strong> — <em>data only</em>. A plain <code>struct</code> with public fields, built with\ndesignated initializers. No business logic, no getters/setters wrapping plain\nfields. This is the unit of <em>value passing and configuration</em>.</li>\n<li><strong>Value / resource type</strong> — a concrete, value-semantic type that either owns a\nresource (an RAII wrapper) or enforces one invariant (a strong type: <code>Money</code>,\n<code>EmailAddress</code>, a math <code>Vector3</code>, a C-handle wrapper). It has a small, total\ninterface and behaves like a built-in — the <em>Regular</em> type. This is the one\nconcrete-class-with-methods that earns its keep.</li>\n</ul>\n<p>Reject the muddy middle that models reach for by default: a concrete class that\nmixes private fields, a grab-bag of public methods, <em>and</em> a scatter of free\nhelper functions — neither a clean interface, nor plain data, nor a focused value\ntype. That shape is the single biggest tell of AI-slop C++.</p>\n<p>So a concrete class with methods is allowed only when it is <strong>(a)</strong> the\nimplementation of an abstract class (<code>struct FooImpl final : Foo</code>, defined\nin a <code>.cpp</code>, never a header), or <strong>(b)</strong> a value/resource type as above.\nEverything else is behavior behind an interface, or data in a struct.</p>\n<h2>What you are overriding</h2>\n<table>\n<thead>\n<tr>\n<th>AI-slop default</th>\n<th>This skill</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Free functions <code>dep1DoX()</code>, <code>dep2DoX()</code></td>\n<td>One abstract interface <code>Dep</code>, injected</td>\n</tr>\n<tr>\n<td>Concrete class with public mutable fields + methods</td>\n<td>Abstract class (behavior) <strong>or</strong> data struct (data)</td>\n</tr>\n<tr>\n<td><code>Dog dog; dog.doThing(globalThing);</code></td>\n<td>Inject the collaborator: <code>dog.doThing(dep)</code></td>\n</tr>\n<tr>\n<td><code>void f(string n, int a, int p, int addr)</code></td>\n<td><code>void f(FooConfig const &amp;cfg)</code> (designated init)</td>\n</tr>\n<tr>\n<td><code>new T</code> / <code>delete</code> / <code>new T[]</code></td>\n<td><code>make_unique</code> / <code>make_shared</code> / <code>vector&lt;T&gt;</code></td>\n</tr>\n<tr>\n<td><code>int parseInt()</code> returning <code>-1</code> on failure</td>\n<td><code>optional&lt;int&gt; parseInt()</code></td>\n</tr>\n<tr>\n<td><code>enum Mode</code> + <code>switch</code> dispatch</td>\n<td>inject a strategy / functor, or a state class</td>\n</tr>\n<tr>\n<td><code>pair&lt;bool, It&gt;</code> / <code>tuple&lt;...&gt;</code> returns</td>\n<td>named result struct</td>\n</tr>\n<tr>\n<td><code>const T&amp; x</code>, <code>const T* p</code></td>\n<td>East const: <code>T const &amp;x</code>, <code>T const *p</code></td>\n</tr>\n</tbody>\n</table>\n<h2>Named anti-patterns (real smells this overrides)</h2>\n<p>These are the concrete shapes that mark sloppy or dated C++ — name them and\nrefuse them:</p>\n<ul>\n<li><strong>God-base interface</strong> — one abstract class fusing <em>data and behavior</em>, with a\npile of public mutable members (e.g. a node base every node both reads state\nfrom and overrides). Split it: behavior → interface, state → data struct.</li>\n<li><strong>Global object + free functions</strong> — a global instance poked by a scatter of\nfree helpers. Make it a class with a clear owner and inject it.</li>\n<li><strong>Stringly-typed API</strong> — <code>setParam(\"mode\", \"fast\")</code>, sockets/params keyed by\nstring. Use <code>enum class</code>, strong types, and named fields so the compiler\nchecks them. Relatedly, <strong>fetch an abstract handle once</strong> rather than re-passing\na string key on every call: <code>auto *dev = api-&gt;getDevice(\"CD\"); dev-&gt;play();</code>,\nnot <code>api-&gt;playDevice(\"CD\")</code> then <code>api-&gt;stopDevice(\"CD\")</code>.</li>\n<li><strong>Sentinel returns</strong> — <code>(size_t)-1</code>, <code>-1</code>, empty string, or null on failure.\nUse <code>optional</code> / <code>expected</code> or a result struct (see <code>references/error-handling.md</code>).</li>\n</ul>\n<h2>The canonical shape</h2>\n<pre><code>// Dep.h — interface only. Pure virtual. Lives in a small header.\nstruct MethodConfig {\n    Point position{};\n    float size{};\n};\n\nstruct Dep {\n    virtual ~Dep() = default;\n    virtual std::string someQuery() const = 0;\n    virtual void someMethod(MethodConfig const &amp;config) = 0;\n};\n\n// Animal.h\nstruct Animal {\n    virtual ~Animal() = default;\n    virtual void someInterface(Dep *dep) = 0;   // collaborator injected, not owned\n};\n\n// Dog.h — concrete impl, declared minimally, defined in .cpp\nstruct Dog final : Animal {\n    void someInterface(Dep *dep) override;\nprivate:\n    int somePrivate{};\n};\n\n// Dog.cpp\nvoid Dog::someInterface(Dep *dep) {\n    auto answer = dep-&gt;someQuery();   // reuse, don't reimplement per concrete dep\n    // ...\n}\n\n// callSite.cpp — the composition root wires concrete to abstract\nauto dog = Dog{};\nauto dep1 = std::make_unique&lt;Dep1&gt;(someOptions);\ndog.someInterface(dep1.get());\n</code></pre>\n<h2>Class design</h2>\n<p><strong>Virtual functions are a backbone of this style — reach for them.</strong> They do\n<em>two</em> distinct jobs, and both are worth an interface:</p>\n<ol>\n<li><p><strong>Dispatch / dependency injection</strong> — one shared caller works across subtypes\nit doesn't know. This is what replaces <em>branching on a type tag</em>\n(<code>switch (getType())</code>, <code>if (type == Dog)</code>) to pick behavior: let the vtable\ndispatch, so adding a subtype touches no existing branch. Without it, every new\nsubtype copy-pastes the shared logic and one requirement change means editing N\nfiles. The payoff is <strong>open for extension, closed for modification</strong> —\na new subtype, even one written later by another module or plugin, slots in\nbehind the interface without reopening any caller.</p>\n<pre><code>void feed(Animal *a) { puts(\"feeding\"); a-&gt;speak(); puts(\"done\"); }\n</code></pre>\n</li>\n<li><p><strong>Implementation hiding</strong> — the interface lives in the header, the concrete\n<code>…Impl</code> lives in the <code>.cpp</code>. This is worthwhile <em>even with a single\nimplementation</em>: a compile firewall (member types and heavy/third-party\nheaders stay out of your public header, callers don't recompile when the impl\nchanges), a clean ABI boundary, and a ready test seam. (See\n\"single-implementation interface\" below.)</p>\n</li>\n</ol>\n<p>The only thing to avoid is the <em>empty</em> interface — a <code>virtual</code> that delivers\nneither job: you already hold the concrete type, there is exactly one\nimplementation, and you gain no hiding, seam, or ABI benefit. That is pure\noverhead. Everywhere a real seam exists — polymorphism <strong>or</strong> build/ABI/test —\nprefer the interface.</p>\n<p><strong>Escalate abstraction only as far as the duplication demands.</strong> Lift a repeated\nvalue to a variable, repeated logic to a function, a clump of arguments to a\nstruct, shared state-plus-behavior to a class, a fixed set of variants to an\n<code>enum</code>, a fixed set of <em>types</em> to a <code>std::variant</code>, and an open set of behaviors\nto a <code>virtual</code> interface — in that order. Don't jump to the interface when a\nfunction would do. The real cost of copy-paste is not the typing — it is the typo\nyou later make in one rarely-run branch. When the type set is closed and known at\ncompile time, resolve it at compile time — a <code>variant</code> or <code>concept</code>-constrained\noverloads (not an <code>if constexpr</code> type-switch; see\n<code>references/generics-compile-time.md</code>).</p>\n<p><strong>One interface, one responsibility.</strong> Never mix concerns (e.g. IO <em>and</em>\ncomputation) in one abstract class — it forces an N×M subclass explosion. Split\ninto independent interfaces and let a high-level function combine them:</p>\n<pre><code>struct Inputer { virtual ~Inputer() = default; virtual std::optional&lt;int&gt; fetch() = 0; };\nstruct Reducer { virtual ~Reducer() = default; virtual int init() = 0; virtual int add(int, int) = 0; };\nint reduce(Inputer *in, Reducer *r);   // 2+2 classes, unlimited combinations\n</code></pre>\n<p><strong>Template Method — public non-virtual wrapper, protected virtual <code>do_xxx</code>.</strong>\nThe public method owns the contract and supplies ergonomic overloads; subclasses\noverride only the raw <code>do_xxx</code>. (As in <code>std::pmr::memory_resource</code>.)</p>\n<pre><code>struct Converter {\n    void process(std::string_view sv) { do_process(sv.data(), sv.size()); }\n    void process(char const *s)       { do_process(s, std::strlen(s)); }\nprotected:\n    virtual void do_process(char const *s, size_t n) = 0;\n};\n</code></pre>\n<p><strong>Strategy vs Template Method — which to pick.</strong> Many independent behaviors on one\nobject → <em>Strategy</em>: hold pointers to injected strategy interfaces (a <code>Character</code>\nwith separate <code>move</code> and <code>attack</code> strategies). A single behavior that needs the\nobject's own members → <em>Template Method</em>: the base <em>is</em> the strategy, the\n<code>virtual</code> reads its own fields (a <code>Weapon</code> whose <code>attack</code> uses its <code>damage</code> /\n<code>range</code>). One axis of variation that owns no state → functor; several axes, or\nstate-carrying behavior → strategy objects.</p>\n<p><strong>Thin virtual core, fat non-virtual API.</strong> Put only primitives behind <code>virtual</code>\n(<code>do_read</code>, <code>do_write</code>, <code>do_seek</code>); build the rich convenience API\n(<code>getline</code>, <code>flush</code>) as non-virtual methods on top. Few virtuals, much reuse.</p>\n<p><strong>Compose, don't multiply subclasses.</strong></p>\n<ul>\n<li><em>Adapter</em>: wrap an interface, return the same interface, add one capability.\nAdapters compose orthogonally instead of <code>N×M</code> subclasses.</li>\n<li><em>State as class</em>: encode states as classes implementing a <code>State</code> interface,\nnot <code>enum + switch</code>. Adding a state touches no existing branch.</li>\n<li><em>Component</em>: a <code>GameObject</code> holds <code>vector&lt;unique_ptr&lt;Component&gt;&gt;</code>. Use dynamic\ncomposition for behavior, <strong>never multiple inheritance.</strong></li>\n<li><em>CRTP</em>: auto-implement boilerplate virtuals (<code>clone</code>, <code>accept</code>) once in a\n<code>template &lt;class D&gt; struct Impl : Base</code> mixin instead of per subclass.</li>\n<li><em>Visitor / double-dispatch</em>: when behavior depends on two types (or you'd\notherwise write <code>getType()</code> / <code>isEatable()</code> and switch on it), use\n<code>accept</code>/<code>visit</code> so the compiler picks the overload — don't query a type tag.</li>\n<li><em>Closed-set variant</em>: a fixed, known set of types → <code>std::variant</code> + <code>std::visit</code>\ninstead of a class hierarchy — value semantics, no heap or vtable. Use a\n<code>virtual</code> interface instead when the set is open. (See\n<code>references/generics-compile-time.md</code>.)</li>\n<li><em>Flyweight</em>: when many objects share identical heavy data (a texture, a lookup\ntable), hoist it into a separate type held by a <code>shared_ptr</code>; keep only the\nper-instance data (position, velocity) local. 1000 bullets, one shared sprite —\nnot 1000 texture copies. The owner's method just <em>forwards</em> to the shared object\n(<code>sprite-&gt;draw(position)</code>) — that delegation is the <em>proxy</em> idiom.</li>\n</ul>\n<p><strong>Interface/implementation split (header hygiene).</strong> Put the pure-virtual\ninterface in a small header; keep the concrete <code>…Impl final</code> entirely in the\n<code>.cpp</code>. Hand back the interface through a <strong>factory</strong>, so callers never see — or\n<code>#include</code> — the concrete type:</p>\n<pre><code>// Foo.h\nstruct Foo { virtual ~Foo() = default; virtual void run() = 0; };\nstd::unique_ptr&lt;Foo&gt; createFoo(FooConfig const &amp;cfg);   // factory returns the interface\n</code></pre>\n<p>This is also how you select backends: define the factory once per backend\ndirectory and let the build system link exactly one. Swapping an implementation\n(real vendor SDK ↔ a fake for tests/replay) becomes a build-variable change, not\na code change — the test double is just another implementation behind the seam.</p>\n<p><strong>A single-implementation interface is justified — for hiding, not dispatch.</strong>\nEven when only one <code>…Impl</code> will ever exist, the compile-firewall / ABI / test-seam\npayoff of point 2 still earns the interface — the deliberate exception to \"don't\nover-abstract.\" The public header carries only the interface and a factory; the\nsole <code>…Impl</code> and its heavy headers stay in the <code>.cpp</code>:</p>\n<pre><code>// Widget.h — interface + factory are the whole public surface\nstruct Widget {\n    virtual ~Widget() = default;\n    virtual void draw() = 0;\n};\nstd::unique_ptr&lt;Widget&gt; makeWidget(WidgetConfig const &amp;cfg);\n\n// Widget.cpp — the lone impl and its &lt;heavy/thirdparty.h&gt; are hidden here\nstruct WidgetImpl final : Widget {\n    heavy::thirdparty::Object object;\n\n    explicit WidgetImpl(WidgetConfig const &amp;cfg) { /* ... */ }\n    void draw() override { /* ... */ }\n};\n\nstd::unique_ptr&lt;Widget&gt; makeWidget(WidgetConfig const &amp;cfg) {\n    return std::make_unique&lt;WidgetImpl&gt;(cfg);\n}\n</code></pre>\n<p>Prefer this over classic value-semantic PIMPL since it allows a test fake or a\nsecond backend later; plain PIMPL gives <em>only</em> the compile firewall, no seam.</p>\n<p><strong>Command/callback pairs (Api / Spi).</strong> For a subsystem with inversion of\ncontrol, split the two directions into two interfaces: an <strong><code>Api</code></strong> (the\n<em>application programming interface</em> — commands you call <em>into</em> the subsystem) and\nan <strong><code>Spi</code></strong> (the <em>service provider interface</em> — events the subsystem calls <em>back</em>\nout to you). The owner implements the <code>Spi</code> and holds the <code>Api</code>; wire the two with\n<code>api-&gt;setSpi(this)</code>.</p>\n<pre><code>struct PlayerSpi {                       // you implement — called back on events\n    virtual ~PlayerSpi() = default;\n    virtual void onTrackEnded() = 0;\n};\nstruct PlayerApi {                       // you call in — commands\n    virtual ~PlayerApi() = default;\n    virtual void setSpi(PlayerSpi *spi) = 0;\n    virtual void play(Track const &amp;t) = 0;\n};\n\nstruct App final : PlayerSpi {           // owner: implements Spi, holds Api\n    explicit App(PlayerApi *api) : api(api) { api-&gt;setSpi(this); }\n    void onTrackEnded() override { api-&gt;play(next()); }   // reacts to the callback\n    PlayerApi *api;\n};\n</code></pre>\n<p><strong>Singleton — encapsulate the one instance, never a bare global.</strong> For a genuinely\nprocess-wide subsystem, hide the constructor, delete copy/move, and hand out the\ninstance through one accessor — define it in the <code>.cpp</code> like any other method:</p>\n<pre><code>// Game.h\nstruct Game {\n    void update();\n    static Game &amp;instance();        // the sole accessor\n    Game(Game &amp;&amp;) = delete;\nprivate:\n    Game();\n};\n// Game.cpp\nGame &amp;Game::instance() { static Game inst; return inst; }   // lazy, thread-safe (C++11)\n</code></pre>\n<p>A header form — a header-only util, or the generic\n<code>template &lt;class T&gt; T &amp;singleton() { static T inst; return inst; }</code> — must be\n<code>inline</code>, not <code>static</code>, and gets a separate copy per Windows DLL. A singleton is\nstill global state: prefer injection through the composition root, and reserve it\nfor subsystems that are truly one-per-process.</p>\n<h2>Dependency injection</h2>\n<ul>\n<li><strong>Inject abstractions into high-level functions, never concrete types.</strong> The\ncaller chooses the implementation; the callee depends only on the interface.</li>\n<li><strong>Inject a factory, not a product, when the callee must create many.</strong> Give a\n<code>Gun</code> whose <code>virtual unique_ptr&lt;Bullet&gt; shoot()</code> the callee calls repeatedly —\nnot a single pre-made <code>Bullet</code>.</li>\n<li><strong>A single composition root does all the wiring.</strong> One <code>main.cpp</code> (or one\nsetup function) calls the factories and injects via constructor args or\nsetters. No globals reach across modules; production vs test differ only by\nwhich factories the root calls.</li>\n<li><strong>Collaborators are borrowed, not owned.</strong> Pass dependencies as raw interface\npointers (<code>Dep *</code>) or references; the injectee never owns its collaborators.\nOwnership lives in the composition root. (See <code>references/ownership-lifetime.md</code>.)</li>\n</ul>\n<h2>CMake-first project structure</h2>\n<ul>\n<li><strong>Make the target graph mirror the module graph.</strong> Give each architectural\nmodule its own directory, <code>CMakeLists.txt</code>, and library target; let executable\ntargets be composition roots that link those modules.</li>\n<li><strong>Keep public structure explicit.</strong> Put exported headers under\n<code>include/&lt;module&gt;/</code>, implementations under <code>src/</code>, include them as\n<code>&lt;module/Foo.h&gt;</code>, and use the module name as the C++ namespace.</li>\n<li><strong>Attach requirements to the target that owns them.</strong> Sources, include paths,\ndefinitions, options, and dependencies use <code>target_*</code>; choose <code>PRIVATE</code>,\n<code>PUBLIC</code>, or <code>INTERFACE</code> from whether consumers need the requirement.</li>\n<li><strong>Name repeated configuration profiles with CMake Presets.</strong> When developers\nrepeatedly choose among several options, build types, or toolchains, commit a\n<code>CMakePresets.json</code> so configure, build, and test use short named profiles with\nseparate build trees instead of reconstructed <code>-D...</code> command lines.</li>\n<li><strong>Prefer an <code>OBJECT</code> library for an internal module folded into final products\nin one build tree.</strong> Multiple in-tree apps, tests, or probes do not require an\narchive. Use <code>STATIC</code> or <code>SHARED</code> when the library is itself a deliberate\narchive, runtime, ABI, installation, or deployment boundary.</li>\n<li><strong>Normalize each third-party dependency to one CMake target.</strong> Prefer an\nupstream target whether its source is vendored with <code>add_subdirectory</code> or\ndiscovered as an installed package. Wrap header-only trees, pkg-config data,\nlegacy variables, and raw binary SDKs behind a target instead of scattering\ninclude paths and flags across consumers.</li>\n<li><strong>Give each logical dependency one provider and version in the final graph.</strong>\nResolve diamonds at the composition root; do not let two parents silently\nembed incompatible copies of the same library.</li>\n<li><strong>Choose the delivery contract before adding packaging machinery.</strong> Public\nlibraries and geek-oriented CLI tools get a textbook install target and source\narchive; end-user applications get a dedicated artifact pipeline; pybind11\nextensions are installed into a Python wheel staging tree.</li>\n</ul>\n<p>Read <code>references/cmake-first-projects.md</code> before creating or restructuring a\nCMake C++ project, changing module targets, or deciding dependency visibility.\nFor acquiring, building, finding, vendoring, or wrapping a third-party library,\nor for diagnosing a binary dependency ABI mismatch, read\n<code>references/dependencies/router.md</code> first.\nFor any install, package, release archive, portable bundle, AppImage, native\ninstaller, or Python-extension distribution task, read\n<code>references/deployment/router.md</code> first. It routes further by deliverable type\nand distribution scope.</p>\n<h2>Type-rich data classes</h2>\n<p>Make illegal states unrepresentable and make call sites self-documenting. The\ncompiler is your reviewer.</p>\n<ul>\n<li><strong>Bundle ≥3 related params into a named struct with designated init.</strong> Names\nbeat positions; adding a defaulted field breaks zero callers.\n<code>void foo(FooConfig const &amp;cfg);</code> then <code>foo({.name = \"x\", .age = 24});</code></li>\n<li><strong>Return a named struct, never <code>pair</code>/<code>tuple</code>.</strong> <code>result.success</code> not\n<code>result.first</code>.</li>\n<li><strong><code>optional&lt;T&gt;</code> for nullable returns</strong> — never a sentinel like <code>-1</code> or a\nnullable raw pointer. (Error handling: <code>references/error-handling.md</code>.)</li>\n<li><strong>Don't reflexively wrap fields in <code>optional&lt;T&gt;</code></strong> — reserve it for genuinely\nsometimes-absent data; on an always-present field it just sprays null-checks. A\nreal either/or is a <code>std::variant</code> or distinct types, not a nullable.</li>\n<li><strong><code>enum class</code> for flags/states</strong> — blocks implicit <code>int</code> conversion and\nargument-order bugs.</li>\n<li><strong>Strong types for primitives that should not interconvert.</strong> Wrap in a\none-member struct or <code>enum class FileHandle : int {}</code> so <code>read(fd, …)</code> can't\nsilently take the wrong <code>int</code>.</li>\n<li><strong><code>std::span&lt;T&gt;</code> / <code>string_view</code> for non-owning buffer/string params</strong> —\nlength travels with the data, no <code>ptr,len</code> mismatch.</li>\n<li><strong><code>std::chrono</code> for time</strong>, never raw integers — <code>time_point + time_point</code>\nbecomes a compile error instead of a 54-year sleep.</li>\n<li><strong>Plain data is a <code>struct</code> with public fields</strong>, constructed by aggregate\ninitialization — <code>Foo{a, b}</code> or designated <code>Foo{.x = a, .y = b}</code> — with no\nhand-written constructor and no encapsulation ceremony.</li>\n<li><strong>Getters/setters earn their place only to guard an invariant</strong> — inside a\nvalue/resource type. Independent fields stay public (a <code>Point</code>'s <code>.x</code>/<code>.y</code> need\nno <code>getX</code>/<code>setX</code>); fields coupled by an invariant hide behind hook methods with\nmutation banned (a <code>vector</code> exposes <code>size()</code>/<code>resize()</code> and a read-only <code>data()</code>\nbecause resizing must reallocate).</li>\n<li><strong>Name constructors by intent — use named static factories</strong> when variants\ndiffer in meaning, not signature (<code>Cake::makeChoco()</code> / <code>Cake::makeMoca()</code>,\nnot <code>Cake(double)</code> vs <code>Cake(int)</code>).</li>\n</ul>\n<h2>Naming &amp; layout</h2>\n<ul>\n<li><strong>No <code>m_</code> prefix, no trailing-underscore on members.</strong> Members are bare names.</li>\n<li><strong>Trailing underscore only on a ctor/setter param that shadows a member:</strong>\n<code>void setX(double x_) { x = x_; }</code>.</li>\n<li>Types <code>PascalCase</code>; methods &amp; members <code>camelCase</code>; constants <code>kPascalCase</code>;\n<code>enum class : uint8_t</code> with explicit underlying type.</li>\n<li>Predicate methods read as intent: <code>shouldRetry()</code>, <code>canFlush()</code>.</li>\n<li><strong>One concept per header</strong>, kept small. <code>#pragma once</code>, never include guards.</li>\n<li><strong>Forward-declare in headers, <code>#include</code> in the <code>.cpp</code></strong> to cut compile\ncoupling.</li>\n<li><strong>East const everywhere:</strong> <code>T const &amp;</code>, <code>T const *</code> — const binds to what\nprecedes it, which reads consistently right-to-left.</li>\n<li><strong>Always <code>struct</code>, never the <code>class</code> keyword</strong> — even for encapsulated types.\nOpen an explicit <code>private:</code> / <code>protected:</code> section when you need encapsulation\n(<code>struct Game { void play(); private: Game(); };</code>). The keyword carries nothing\nthe access labels don't, and defaulting to <code>struct</code> keeps each type's public\nsurface first and visible.</li>\n<li>In headers, share definitions with <code>inline</code>, never <code>static</code> (which silently\nduplicates per translation unit).</li>\n</ul>\n<h2>Use <code>auto</code> wisely in local variables</h2>\n<p>For an ordinary local value, use one of two declaration forms (adding <code>const</code>\naccording to the next section):</p>\n<pre><code>auto x = rhs;       // deduced form: the type is locally evident\nType x{rhs};        // named receiving form: the type adds missing semantics\n</code></pre>\n<p>Use the deduced form when the RHS names the type, the producer and its type are\nevident within the same function body, or the exact type is lengthy, unnamed, or\ndeliberately an implementation detail:</p>\n<pre><code>auto const i = std::size_t{1};\nauto worker = std::make_unique&lt;Worker&gt;(config);\nauto values = std::vector&lt;int&gt;(3); // `()` intentionally selects the count ctor\n</code></pre>\n<p>Use the named receiving form when a reader cannot recover the type from the\ncurrent function without inspecting a callee, and the type is important to the\nmeaning of the code:</p>\n<pre><code>State const state{machine.state()};\n</code></pre>\n<p>The named form receives an existing expression. When supplying constructor\narguments, put the constructed type on the RHS: <code>auto dog = Dog{\"George\", 10};</code>.\nDo not write <code>Type x = rhs</code>, <code>Type x(rhs)</code>, or an uninitialized <code>Type x</code>; those\nforms can hide conversions, misuse parentheses, or leave built-in values\nindeterminate. Braces make narrowing conversions ill-formed:</p>\n<pre><code>std::size_t const count{fetchCount()};\n// int count = fetchCount();              // implicit narrowing\n// int count(fetchCount());               // implicit narrowing\nint const count{static_cast&lt;int&gt;(fetchCount())}; // only after a range check\n</code></pre>\n<p>Do not optimize for silently surviving return-type changes. A named receiving\ntype should make narrowing API drift a compile error instead of an implicit\nconversion. Braces do not require exact type equality; use strong types when\neven otherwise-valid conversions must be rejected.</p>\n<p><code>auto</code> deduction does not preserve top-level <code>const</code> or references. In\nrange-for, use <code>auto const &amp;</code> to read and <code>auto &amp;</code> to modify; bare <code>auto</code> copies.\nFor maps: <code>for (auto const &amp;[key, value] : map)</code>.</p>\n<h2>The <code>const</code> idiom</h2>\n<ul>\n<li><strong>Almost Always Const:</strong> write <code>auto const value = makeValue();</code> unless the\nbinding must later be reassigned or moved from. Mutation should be deliberate\nand visible at the declaration.</li>\n<li><strong>Declare every pass-by-value parameter <code>const</code>:</strong> spell it <code>T const</code>,\n<code>std::span&lt;T&gt; const</code>, or <code>T const *const</code>. Top-level <code>const</code> freezes the local\nparameter binding; element or pointee constness remains a separate choice.</li>\n<li><strong>Prefer new <code>const</code> variables over of reuse:</strong> declare new local variables\nfor logically different variable instead of re-assigning existing ones. Only\nreuse when a loop or iteration involves iterative update of a same variable.</li>\n<li><strong>Mark every observation-only member function <code>const</code>.</strong> A query may not\nmutate the object's observable value; require the same qualifier on interface\ndeclarations and overrides.</li>\n<li><strong>Expose read-only access with a const view:</strong> <code>T const &amp;</code>, <code>T const *</code>,\n<code>std::span&lt;T const&gt;</code>, or <code>std::string_view</code>. Return mutable access only when\nmutation is an explicit part of the API contract.</li>\n<li><strong>Leave a local non-const when ownership must move from it.</strong> <code>const</code> blocks\nmoving from move-only values and may turn an intended move into a copy; never\nreturn <code>T const</code> by value for the same reason.</li>\n<li><strong>Reserve <code>mutable</code> only for logical constness</strong>, such as a cache or mutex that\ndoes not change the observable value. Never for hiding ordinary state changes.</li>\n</ul>\n<h2>Signature clarity</h2>\n<p>Function signatures should be self-explained. An interface should convey its expected behavior from its declaration. A function should explain its purpose solely from name and types without ambiguity.</p>\n<p><strong>Why:</strong> when writing code, reading the header can explains the expected behavior for most trivial functions.</p>\n<p>Use a name telling full story e.g. <code>Process::isRunning()</code> instead of <code>Process::check()</code>, unless the class already locks the context e.g. <code>OutOfOrderChecker::check()</code>.</p>\n<p>Avoid ambiguious function and class names, rename them immediately once you flag one.</p>\n<p><strong>Why:</strong> a confusing interface name may confuse future agents to risk misuse them.</p>\n<p>When there are ambiguity of generic type in argument, define and use type-rich classes <code>sleep(Duration const &amp;)</code>, <code>findByName(Name const &amp;)</code>.</p>\n<p>When there are multiple argument whose order and meaning are ambiguious, use <code>fill(Rect const &amp;)</code> and invoke with <code>Rect{...}</code>.</p>\n<p><strong>Why:</strong> saves future agent from drifting type semantics during refactor.</p>\n<h2>Duty class</h2>\n<p>Keep class interface small and orthogonal. Alert god-class tendency. When a class is piling too many methods and can be classified into orthogonal categories, consider breakdown heavy duty cluster into duty class.</p>\n<p>E.g. <code>std::unique_ptr&lt;Painter&gt; Canvas::getPainter()</code> + <code>Painter::fill(Path const &amp;, Brush const &amp;)</code> + <code>Painter::stroke(Path const &amp;, Pen const &amp;)</code>. Here <code>Painter</code> can be another abstract class, and <code>Canvas</code> implements <code>Paintable</code> which requires <code>Paintable::getPainter()</code>. <code>Canvas.cpp</code> can implement that as <code>CanvasPainter</code> privately using anonymous namespace (a typical implementation can holds a <code>Canvas *</code> pointer). This keeps the <code>Canvas</code> interface stay focused, also reserve for future <code>Paintable</code> implementations.</p>\n<p><strong>Why:</strong> programmers and LLMs works better when knowledge is progressively disclosed. Reading a god-class floods context by side-cars unrelevant to the goal. So keep interface small and hierarchy to avoid dilution.</p>\n<h2>Don't repeat yourself</h2>\n<p>When there are more than 2~3 paths sharing common pattern or concept: extract into abstracted class. E.g. <code>Path</code> for <code>Line</code>, <code>Arc</code>, <code>Bezier</code>; <code>Brush</code> for <code>Color</code>, <code>Gradient</code>; saves <code>fill()</code> from combination hell.</p>\n<p>Two approaches to abstraction:</p>\n<ul>\n<li>Potentially vast expansion in future -&gt; <strong>Dynamic polymorphism</strong>: <code>Path</code> as abstract class; pointer semantics; pass as <code>Path const &amp;</code> (or <code>Path *</code> if mutable); return and store as <code>std::unique_ptr&lt;Path&gt;</code>.</li>\n<li>Fixed types, likely won't expand -&gt; <strong>Static polymorphism</strong>: <code>Brush</code> as a data-class wrapped <code>std::variant</code>; value semantics; pass as <code>Brush const &amp;</code>; return and store as <code>Brush</code>.</li>\n</ul>\n<p>Avoid using function overload and templates for polymorphism unless the context is metaprogramming or performance.</p>\n<h2>Boolean expression style</h2>\n<p>Prefer the C++ alternative operator tokens <code>not</code>, <code>and</code>, and <code>or</code> in\nhuman-written boolean expressions. They are core-language keywords with exactly\nthe same semantics and precedence as <code>!</code>, <code>&amp;&amp;</code>, and <code>||</code>, but they are harder to\nmiss while scanning:</p>\n<pre><code>if (not isReady() or (isExpired() and canRetry())) {\n    return false;\n}\n</code></pre>\n<ul>\n<li>Parenthesize mixed <code>and</code> / <code>or</code> expressions even when precedence already gives\nthe intended result.</li>\n<li>Prefer a positive named predicate over a dense negation; introduce\n<code>isUnavailable()</code> when it communicates a recurring domain concept better than\n<code>not isAvailable()</code>.</li>\n<li>Keep <code>!=</code> and bitwise operators symbolic. Do not generalize this rule to\nuncommon spellings such as <code>not_eq</code>, <code>bitand</code>, or <code>xor</code>.</li>\n<li>This rule is for boolean expressions, not rvalue references (<code>T &amp;&amp;</code>) or\ndeclarations such as <code>operator&amp;&amp;</code>. Match third-party and generated code rather\nthan rewriting it solely for house style.</li>\n</ul>\n<h2>Prefer brace initialization</h2>\n<p>Prefer direct-list initialization (<code>{}</code>) over direct initialization (<code>()</code>) when\nthe two forms select the same constructor:</p>\n<pre><code>struct Dog {\n    explicit Dog(std::string name, std::int32_t age);\n};\n\nauto dog = Dog{\"George\", 10};  // NEVER: Dog dog(\"George\", 10);\n</code></pre>\n<p>This is <strong>list initialization</strong>, not an \"aggregate constructor.\" Aggregate\ninitialization is only the constructor-free data-class case such as\n<code>Point{.x = 1, .y = 2}</code>. <code>Dog</code> above has a user-declared constructor and is not\nan aggregate.</p>\n<p>Use <code>()</code> when braces intentionally select an <code>initializer_list</code> overload with\ndifferent semantics. <code>std::vector</code> is the canonical example:</p>\n<pre><code>auto oneValue = std::vector&lt;std::int32_t&gt;{3}; // one element: {3}\nauto threeZeros = std::vector&lt;std::int32_t&gt;(3); // three elements: {0, 0, 0}\n\nauto twoValues = std::vector&lt;std::int32_t&gt;{3, 42}; // {3, 42}\nauto threeValues = std::vector&lt;std::int32_t&gt;(3, 42); // {42, 42, 42}\n</code></pre>\n<p>An implicit constructor permits copy-list initialization at a call site. This is\nnot aggregate initialization either:</p>\n<pre><code>struct Dog {\n    Dog(std::string const &amp;name, int age);\n};\n\nvoid showDog(Dog const &amp;dog);\n\nshowDog({\"George\", 10});\n\nauto dogs = std::vector&lt;Dog&gt;();\ndogs.push_back({\"George\", 10});\n</code></pre>\n<h2>When to use <code>explicit</code> constructor</h2>\n<ul>\n<li><strong>Default to <code>explicit</code></strong> for every converting constructor, including\nmulti-argument constructors used through <code>{...}</code>.</li>\n<li>Allow implicit conversion only when the source and destination are genuinely\nsubstitutable values and the conversion is unsurprising and lossless, such as\na UTF-8 string literal becoming an owning <code>std::string</code>.</li>\n<li>Different semantics require <code>explicit</code>: a count is not a container, a raw\nhandle is not an owning resource, and an integer is not an age merely because\ntheir representation matches.</li>\n<li>When construction modes differ by intent, use named factories rather than\nconstructor overloads: <code>Angle::fromDegrees(x)</code> and <code>Angle::fromRadians(x)</code>.</li>\n</ul>\n<pre><code>struct BigInt {\n    BigInt(std::int32_t value); // exact, lossless value-domain extension\n};\n\nstruct Dog {\n    explicit Dog(std::string const &amp;name);\n};\n\nvoid sendMsg(std::string const &amp;msg);\nvoid showBigInt(BigInt const &amp;big);\nvoid showDog(Dog const &amp;dog);\n\nvoid usage() {\n    sendMsg(\"hello\");\n    showBigInt(42);\n    showDog(Dog{\"George\"});\n}\n</code></pre>\n<h2>C++ cast ladder</h2>\n<p>Pick casts by the semantic conversion being requested. For arithmetic values,\n\"up-cast\" and \"down-cast\" are misleading: signedness, range, precision, and the\nruntime value all matter.</p>\n<ul>\n<li><p><strong>Known-safe constant → braces.</strong> List initialization rejects narrowing at\ncompile time: <code>auto channel = std::uint8_t{42};</code> is valid while\n<code>std::uint8_t{300}</code> is ill-formed.</p>\n</li>\n<li><p><strong>Runtime integral conversion → check, then <code>static_cast</code>.</strong> In C<ins>20 use\n<code>std::in_range</code>; in C</ins>17 compare against <code>numeric_limits</code> with signedness\nhandled explicitly:</p>\n<pre><code>std::optional&lt;std::size_t&gt; toSize(std::int32_t value) {\n    if (not std::in_range&lt;std::size_t&gt;(value)) return std::nullopt;\n    return static_cast&lt;std::size_t&gt;(value);\n}\n</code></pre>\n</li>\n<li><p><strong>Floating-point → integer → define the policy first.</strong> Reject non-finite and\nout-of-range values, then choose truncation, floor, ceil, or rounding before\nthe final <code>static_cast</code>. A naked cast silently bakes in truncation and is\nundefined when the finite result is outside the destination range.</p>\n</li>\n<li><p><strong>Representation conversion → <code>std::bit_cast</code></strong> only between equally sized,\ntrivially-copyable types. In C++17 use <code>std::memcpy</code> with the same static\nassertions. This is not numeric conversion.</p>\n</li>\n</ul>\n<p>For a polymorphic <code>Dog : Animal</code> hierarchy:</p>\n<ul>\n<li>Derived-to-base pointer/reference conversion is implicit. Returning\n<code>unique_ptr&lt;Animal&gt;</code> from a factory deliberately hides <code>Dog</code>.</li>\n<li>Prefer virtual dispatch over recovering the concrete type. When a boundary\ngenuinely requires checked base-to-derived conversion, <code>dynamic_cast&lt;Dog *&gt;(p)</code>\nreturns <code>nullptr</code> on mismatch; <code>dynamic_cast&lt;Dog &amp;&gt;(r)</code> throws <code>std::bad_cast</code>.</li>\n<li>Use <code>static_cast&lt;Dog *&gt;(p)</code> only when a nearby invariant proves the dynamic\ntype. Assert that invariant where it is established; a wrong unchecked\ndowncast has undefined behavior.</li>\n</ul>\n<p>Avoid <code>reinterpret_cast</code>. Its legitimate uses are narrow low-level boundaries,\nsuch as the implementation-required pointer/<code>uintptr_t</code> round trip. Converting\nan object pointer to <code>void *</code> is implicit; converting a byte buffer to a packed\nstruct is not a safe zero-copy parser because alignment, lifetime, and aliasing\nstill apply. Copy bytes with <code>memcpy</code>/<code>bit_cast</code>, then validate the fields.</p>\n<p>Avoid <code>const_cast</code>. It is tolerable only when adapting a legacy API whose\nsignature incorrectly omits <code>const</code> and which is known not to write. Modifying an\nobject that was originally defined <code>const</code> is undefined behavior.</p>\n<p>Ban C-style casts <code>(T)x</code>: they can silently combine <code>static_cast</code>,\n<code>const_cast</code>, and <code>reinterpret_cast</code>. Use braces, a named C++ cast, or a\ndomain-specific conversion function that makes validation visible.</p>\n<h2>C++ arithmetic types</h2>\n<p>Choose an integer type from the value's meaning, not from a blanket ban:</p>\n<ul>\n<li>Use <code>std::int8_t</code> / <code>std::uint32_t</code> and friends when an exact width is part of\na wire format, file layout, ABI, SIMD lane, or hardware register. Exact-width\ntypedefs are optional on platforms that cannot provide that width.</li>\n<li>Use <code>int</code> for ordinary small signed arithmetic when no exact width is part of\nthe contract. Do not serialize it or expose its layout as an ABI promise.</li>\n<li>Use a container's <code>size_type</code> (usually <code>std::size_t</code>) for sizes and indices\nthat must interoperate with that container. Use <code>std::ptrdiff_t</code> for signed\ndistances and subtraction. Do not mix signed and unsigned values casually.</li>\n<li>Use <code>std::uintptr_t</code> only when the implementation provides it and an integer\nmust round-trip an object pointer. It is not a generic \"native integer.\"</li>\n<li>Avoid bare <code>long</code> in portable layouts: it differs between LP64 and LLP64.</li>\n</ul>\n<p>Use <code>float</code>, <code>double</code>, or <code>long double</code> according to the required precision,\nrange, ABI, and measured performance. Append <code>f</code> to a floating literal intended\nto be <code>float</code>, such as <code>3.14f</code>; do not rely on an implicit <code>double</code> conversion.</p>\n<h2>Add assert when you made assumption</h2>\n<p>Use <code>static_assert</code> for compile-time properties and <code>assert</code> for internal runtime\ninvariants. Put the check next to the assumption it protects:</p>\n<pre><code>auto const b = someInt();\nauto const a = someInt();\nauto const diff = b - a;\n// Keep a future return-type change from making `diff &lt; 0` always false.\nstatic_assert(std::is_signed_v&lt;decltype(diff)&gt;);\nif (diff &lt; 0) {\n    return false;\n}\n</code></pre>\n<pre><code>auto const v = internalAlgorithm();\nassert(not v.empty());\nreturn v.back() - v.front();\n</code></pre>\n<p><code>assert</code> disappears when <code>NDEBUG</code> is defined. Never use it to validate external\ninput or report a recoverable failure:</p>\n<pre><code>auto const v = fetchFromInternet();\nif (v.empty()) return std::nullopt;\nreturn v.back() - v.front();\n</code></pre>\n<p><strong>Construction as validation:</strong> put one invariant in a value type so downstream\ncode cannot receive an invalid value. Encapsulation earns its place by making\nthe illegal state unrepresentable.</p>\n<pre><code>struct Age {\n    static std::optional&lt;Age&gt; fromYears(std::int32_t value_) noexcept {\n        if (value_ &lt; 0 or value_ &gt; 130) return std::nullopt;\n        return Age{value_};\n    }\n\n    std::int32_t value() const noexcept { return raw; }\n\nprivate:\n    explicit Age(std::int32_t raw_) noexcept : raw(raw_) {}\n    std::int32_t raw;\n};\n\nstruct UserConfig {\n    Email email;\n    UserName name;\n    Age age;\n};\n\nauto const age = Age::fromYears(inputAge);\nif (not age) return false;\nregistry-&gt;registerUser(UserConfig{.email = email, .name = name, .age = *age});\nreturn true;\n</code></pre>\n<p>Return C<ins>23 <code>std::expected</code> when the caller needs an error reason. In C</ins>20/17,\nuse the project's <code>expected</code> backport, a named result struct, or <code>optional</code> when\nno error detail is needed.</p>\n<p><code>UserConfig</code> remains an aggregate data class because each field is independently\nvalid. If validity depends on a relationship among several fields, replace it\nwith one composite value type and a validating named factory; a struct with a\nvalidating constructor is no longer the skill's \"data only\" data class.</p>\n<h2>Function size discipline</h2>\n<p><strong>Function discipline.</strong> Decompose programs into named, single-responsibility\nfunctions — don't pile logic into <code>main</code>, and don't fuse unrelated jobs (a <code>sum</code>\nthat also prints; let the caller decide what to do with the result). Prefer\nearly-return guard clauses over deep nesting, and keep each function within a\nscreenful — Linus's rule of thumb: ≤3 levels of nesting, ≤24 lines, ≤80 columns.</p>\n<h2>Pragmatics — when to dial it back</h2>\n<p>This is a style for code that must live and change. Don't weaponize it:</p>\n<ul>\n<li><strong>Don't pre-abstract.</strong> A one-off internal helper does not need an interface.\nAdd the <em>dispatch</em> seam when a second implementation actually appears (or is\nimminent). This is about polymorphism only — a single-implementation interface\nfor a compile firewall, ABI boundary, or test seam is still justified (see\n\"single-implementation interface\" under Class design).</li>\n<li><strong>Hot paths prefer a template <code>Func</code> over <code>std::function</code>/virtual</strong> for\nzero-overhead dispatch. (See <code>references/functors-callbacks.md</code>.) In a <em>measured</em>\ninner loop it is even fine to drop OOP entirely — raw intrinsics, free\nfunctions, value-semantic SIMD wrappers — provided every such kernel is paired\nwith a reference-checked test and a benchmark. Performance you can't measure is\nnot a reason to abandon the style. (See <code>$cpp-hpc-optimization</code>.)</li>\n<li><strong><code>shared_ptr</code> vs <code>unique_ptr</code>:</strong> prefer a single clear owner (<code>unique_ptr</code>,\nor a process-lifetime raw owning pointer for singletons); reach for <code>shared_ptr</code>\nonly when ownership is genuinely shared.</li>\n</ul>\n<h2>Exemplar libraries — good API to imitate</h2>\n<p>When unsure what a well-designed API looks like, study these. Each is a clean\ndemonstration of one principle:</p>\n<table>\n<thead>\n<tr>\n<th>Library</th>\n<th>Principle it demonstrates</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>fmt</strong> / <code>std::format</code></td>\n<td>type-rich, compile-time-checked format API; no unsafe varargs</td>\n</tr>\n<tr>\n<td><strong>ranges-v3</strong> / <code>std::ranges</code></td>\n<td>composable lazy adaptors over concrete containers</td>\n</tr>\n<tr>\n<td><strong>magic_enum</strong></td>\n<td>type-safe enum reflection without macros or codegen</td>\n</tr>\n<tr>\n<td><strong>nlohmann-json</strong></td>\n<td>RAII ownership and type-deduced <code>get&lt;T&gt;()</code></td>\n</tr>\n<tr>\n<td><strong>tl::expected</strong> / <code>std::expected</code></td>\n<td>value-based error propagation</td>\n</tr>\n<tr>\n<td><strong>structopt</strong></td>\n<td>struct-as-API — a plain data class drives the interface</td>\n</tr>\n</tbody>\n</table>\n<h2>What not to imitate</h2>\n<p>Fine to <em>use</em>; wrong to <em>copy the style of</em>:</p>\n<ul>\n<li><strong>poco</strong> — raw <code>new</code>/<code>delete</code> throughout, Java-style OOP, no value semantics.</li>\n<li><strong>rapidjson / jsoncpp</strong> — SAX template maze / weakly-typed <code>Value</code> tree.</li>\n<li><strong>tinyxml2, legacy OpenCV C API, stb</strong> — raw-pointer, pre-RAII style.</li>\n</ul>\n<p>Qt is a different case: it is <em>excellent</em> <strong>classic</strong> OOP — object-tree ownership,\nsignals/slots, <code>QObject</code> parenting. Its <code>m_</code> members, raw <code>new</code>, and\nparent-owns-child idioms are deliberate and correct <em>for that paradigm</em>. Keep\nthem inside Qt code; just don't carry them into value-semantic modern C++, where\nthis skill's conventions apply.</p>\n<h2>Undefined behavior</h2>\n<p>Establish each operation's bounds, lifetime, type, arithmetic, and synchronization\npreconditions before executing it. Validate external input in release builds;\npassing tests or running without a crash does not prove absence of UB. Classify\nbehavior against the project's C++ version, distinguishing UB from unspecified\nor implementation-defined behavior and compile-time errors.</p>\n<h2>Compiler hygiene</h2>\n<p>Let the compiler enforce the style — most rules above become hard errors instead\nof review comments. Build with:</p>\n<pre><code>-Wall -Wextra -Weffc++\n-Werror=return-type -Werror=uninitialized\n-Werror=suggest-override          # every override marked `override`\n-Wzero-as-null-pointer-constant   # `nullptr`, never `0` / `NULL`\n-Wold-style-cast                  # named casts only, never `(T)x`\n-Werror=vla                       # `std::vector` / `std::array`, never VLAs\n-Wnon-virtual-dtor -Wdelete-non-virtual-dtor\n-Wconversion -Wsign-compare       # no silent narrowing\n-Werror=unused-result             # don't ignore a [[nodiscard]] result\n</code></pre>\n<p>Add <code>-D_GLIBCXX_DEBUG</code> in development builds to catch iterator/bounds misuse at\nruntime (every linked translation unit must match).</p>\n<h2>References</h2>\n<p>You MUST proactively load these when the task touches their area:</p>\n<ul>\n<li><code>references/decoupled-modules.md</code> — definite computation vs tacit I/O or GUI\nboundaries, interface seams, agent-operable harnesses, and integration gates.\nLoad me before decomposing a new C++ project or multi-module architecture.</li>\n<li><code>references/cmake-first-projects.md</code> — course-derived CMake-first directory\nlayout, target kinds, usage requirements, named configuration presets, source\ndiscovery, third-party dependencies, and embeddable subprojects. Load me\nbefore creating or restructuring CMake C++ targets or dependency wiring.</li>\n<li><code>references/dependencies/router.md</code> — third-party dependency router by source\ncontrol, package metadata, graph ownership, and ABI risk. Load me first for\nvendoring, package discovery, manual library integration, binary SDKs,\ndependency diamonds, or C++ ABI mismatches; then follow the matching leaf.</li>\n<li><code>references/deployment/router.md</code> — deployment router by deliverable type,\naudience, and portability scope. Load me first for installation, packaging,\nrelease archives, application artifacts, native installers, or Python wheels;\nthen follow only the matching child routes.</li>\n<li><code>references/debug-instrumentation.md</code> — discriminating state capture, mature\nlogging backends, stable instrument keys, JSONL, and bounded hot-path probes.\nLoad me before adding or structuring temporary diagnostic logs.</li>\n<li><code>references/debug-harnesses.md</code> — minimal harnesses, application or GDB REPLs,\ndurable developer surfaces, customer diagnostics, live calibration, and fast\ndiagnostic builds. Load me when debugging needs controllable execution or when\ndesigning persistent development and support controls.</li>\n<li><code>references/undefined-behavior.md</code> — UB checklist, focused constexpr probes,\nand integrated sanitizer checks. Load me before writing or reviewing\npointer/bounds/lifetime operations, type punning, arithmetic boundaries,\nsequencing, library preconditions, or shared mutable state, and when\ninvestigating suspected UB.</li>\n<li><code>references/ownership-lifetime.md</code> — no raw <code>new</code>, smart pointers vs <code>vector</code>,\nreferences vs pointers, RAII for C resources, the rule of five, dangling\ntemporaries. Load me before smart pointers, or resource management design.</li>\n<li><code>references/functors-callbacks.md</code> — template <code>Func</code> vs <code>std::function</code>,\nlambdas over <code>std::bind</code>, capture lifetime, closures as structs. Load me on\nfunction-programming context.</li>\n<li><code>references/error-handling.md</code> — recoverable vs unrecoverable, <code>optional</code> /\n<code>expected</code>, <code>[[noreturn]]</code>, the result-struct / error-sink / bool+log fallbacks.\nLoad me before I/O interface, business logic, error handling, or third-party error\ncode wrapper.</li>\n<li><code>references/wrapping-c-resources.md</code> — RAII wrappers for opaque C handles:\nmove-only handle template, <code>error_category</code>, check-on-assign with\n<code>source_location</code>, builders, scope-guard binds. Load me before integrating\nthird-party libraries (e.g. OpenGL, CUDA) or manage OS resources with C handles.</li>\n<li><code>references/generics-compile-time.md</code> — compile-time dispatch via\n<code>concept</code>-constrained overloads (not type-switching), <code>if constexpr</code> capability\ngating, <code>std::variant</code> + <code>std::visit</code> closed-set polymorphism, perfect forwarding.\nLoad me when static polymorphism could surpass dynamic polymorphism.</li>\n<li><code>references/type-erasure.md</code> — subtype hiding vs non-intrusive erasure,\nchoosing standard wrappers, and a C++17-compatible interface/model wrapper.\nLoad me when wrapping type erased interface.</li>\n<li><code>references/text-encoding.md</code> — character/code-unit types, UTF-8 storage,\nfilesystem paths, and Qt/platform text boundaries. Load me when handling\nUnicode, encodings, local paths, or text across library/platform boundaries.</li>\n<li><code>$cpp-hpc-optimization</code> — evidence-driven data-oriented layout, numerics,\ncache/locality, SIMD, parallelism, and hot-path polymorphism. Load it before\ndesigning or optimizing a high-throughput kernel or data structure; keep this\nskill's abstract boundaries on the cold/control side and dispatch into\nhomogeneous data batches on the measured hot side. For hot closed-set\npolymorphism, prefer dense per-concrete-type pools such as\n<code>vector&lt;Dog&gt;</code> plus <code>vector&lt;Cat&gt;</code> over per-element base pointers or variants;\nkeep any virtual dispatch at the pool/batch boundary.</li>\n<li><code>references/sources.md</code> — original parallel101 material, exemplar code, and\nfurther-study tools. Load me when verifying provenance or rationale, or when\nlooking for deeper examples behind a rule.</li>\n</ul>\n","files":[{"path":"agents/openai.yaml","sizeBytes":273,"isText":true},{"path":"references/cmake-first-projects.md","sizeBytes":12285,"isText":true},{"path":"references/debug-harnesses.md","sizeBytes":7522,"isText":true},{"path":"references/debug-instrumentation.md","sizeBytes":4456,"isText":true},{"path":"references/decoupled-modules.md","sizeBytes":5457,"isText":true},{"path":"references/dependencies/binary-abi.md","sizeBytes":5035,"isText":true},{"path":"references/dependencies/installed-and-manual.md","sizeBytes":4044,"isText":true},{"path":"references/dependencies/router.md","sizeBytes":3762,"isText":true},{"path":"references/dependencies/source-vendoring.md","sizeBytes":3756,"isText":true},{"path":"references/dependencies/string9811.md","sizeBytes":10235,"isText":true},{"path":"references/deployment/cmake-installable-projects.md","sizeBytes":6381,"isText":true},{"path":"references/deployment/cpp-app-deployment.md","sizeBytes":7957,"isText":true},{"path":"references/deployment/pybind11-packaging.md","sizeBytes":3635,"isText":true},{"path":"references/deployment/router.md","sizeBytes":3915,"isText":true},{"path":"references/error-handling.md","sizeBytes":5304,"isText":true},{"path":"references/functors-callbacks.md","sizeBytes":4883,"isText":true},{"path":"references/generics-compile-time.md","sizeBytes":5399,"isText":true},{"path":"references/ownership-lifetime.md","sizeBytes":5951,"isText":true},{"path":"references/sources.md","sizeBytes":3724,"isText":true},{"path":"references/text-encoding.md","sizeBytes":1671,"isText":true},{"path":"references/type-erasure.md","sizeBytes":2951,"isText":true},{"path":"references/undefined-behavior.md","sizeBytes":12744,"isText":true},{"path":"references/wrapping-c-resources.md","sizeBytes":5925,"isText":true},{"path":"SKILL.md","sizeBytes":45944,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-12-03T18:25:45.665498Z","sha256":"E99F57E8B1FA83CBD9BA67FE33C6AAE27487716483FF992000C2DF33BBF9C274","sizeBytes":77985},"review":null,"source":{"repositoryUrl":"https://github.com/archibate/agent-skills","path":"skills/cpp-oop-style","license":null,"commit":"0a4e08da8a245516055bbfb2203dd7714eb647f5","subtreeSha":"D6D7C33BAC6E21E76B8C7D43F15988C7ED1C4B47285B9F29D06E3E7D9EBC4E8A","lastSyncedAt":"2026-12-03T18:25:06.081922Z"},"reviewedAt":"2026-12-03T18:27:34.992089Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/archibate/agent-skills/tree/master/skills/cpp-oop-style"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install archibate-agent-skills@llmmart"},{"target":"git","command":"git clone https://github.com/archibate/agent-skills.git"}]}