Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # Classes Based on *C++ Primer, 5th ed.* Chapter 7 (Classes). ## 1. Member Functions and the Implicit `this` Pointer - Member functions access the object on which they were called through an extra, implicit parameter named `this`. - It is illegal for us to define a parameter or variable named `this`, because `this` is intended to always refer to "this" object, `this` is a `const` pointer. (`CLASS *const this`) ### `const` Member Functions A **`const` member function** (a member function with `const` placed after the parameter list `()`, e.g., `void bar() const`) changes `this` to `const CLASS *const this` so that the object cannot be modified. ```cpp void Foo::bar(); // Internally: bar(Foo *const this); void Foo::bar() const; // Internally: bar(const Foo *const this); ``` #### `const int bar();` vs. `int bar() const;` Depending on where `const` is placed, it qualifies entirely different entities: | Declaration | Type of `this` | Can Modify Object Members? | Callable on `const` Objects? | Meaning | | :--- | :--- | :---: | :---: | :--- | | **`const int bar();`** | `Foo *const` | ✅ | ❌ | Non-const member function whose **return value** is `const int`. | | **`int bar() const;`** | `const Foo *const` | ❌ | ✅ | `const` member function whose **implicit `this` pointer** points to a `const` object. | #### Implicit vs. Explicit `this->member` Inside a member function body, any direct reference to a class member is implicitly resolved as `this->member`. **You do not need to write `this->` explicitly** unless a local variable or parameter shadows the member name: ```cpp class Point { int x = 0; public: void setX(int val) { x = val; } // Implicitly resolved as this->x = val; (standard practice) void setSame(int x) { this->x = x; } // Explicit this->x required because parameter 'x' shadows member 'x' }; ``` --- ## 2. Constructor - Unlike other member functions, constructors may not be declared as `const`. Constructors can write to `const` objects during their construction. ### `= default;` and Synthesized Default Constructor - **Synthesized default constructor:** The compiler automatically generates a default constructor **only if** a class declares no constructors at all. If any constructor is explicitly defined, the compiler does not synthesize a default constructor. - **`= default;` (C++11):** Explicitly instructs the compiler to generate the synthesized default constructor even when other constructors are defined (`CLASS() = default;`). --- ## 3. Access Control (Access Specifiers) Keywords that control member accessibility (`public`, `protected`, `private`) are formally called **access specifiers** (distinct from type qualifiers such as `const` or `volatile`). ### `public` vs. `protected` vs. `private` - **`public`:** Members defined after `public:` are accessible to all parts of the program (defines the interface). - **`protected`:** Members defined after `protected:` are accessible to the class's member functions, `friend`s, and **derived classes**, while remaining hidden from outside users. - **`private`:** Members defined after `private:` are accessible only to the member functions and `friend`s of the class (encapsulates the implementation from both derived classes and outside users). | Access Specifier | Class Members & `friend`s | Derived Classes | Outside Callers | | :--- | :---: | :---: | :---: | | **`public`** | ✅ | ✅ | ✅ | | **`protected`** | ✅ | ✅ | ❌ | | **`private`** | ✅ | ❌ | ❌ | > **Derivation Access Specifier (`class Derived : public|protected|private Base`):** > When inheriting, the effective access level of an inherited member in the derived class is the **more restrictive (lower) permission** between the **[member's original access level in the base class]** and the **[derivation access specifier]** (`public` > `protected` > `private`). ### `struct` vs. `class` The **only** difference between `struct` and `class` is the default access level: - **`struct`:** Members defined before the first access specifier are **`public`** by default. - **`class`:** Members defined before the first access specifier are **`private`** by default. ### `friend` - A class can allow non-member functions, other classes, or specific member functions of other classes to access its non-public (`private`/`protected`) members by declaring them as `friend`. - `friend` declarations are not affected by access control specifiers (`public`/`private`) and only grant access permission. Because **a `friend` declaration inside a class does not replace a general function declaration**, the function must still be declared separately outside the class to be called. --- ## 4. Additional Class Features ### 1. Type Member A class can define its own local alias for a type (`using` or `typedef`) to hide implementation details. - Unlike ordinary members, a **type member must be defined before it is used** inside the class, so type members usually appear at the beginning of the class body. ```cpp class Screen { public: using pos = std::string::size_type; // or: typedef std::string::size_type pos; private: pos cursor = 0; }; ``` ### 2. `mutable` Data Member - A `mutable` data member is never `const`, even when it is a member of a `const` object. - Therefore, a `const` member function can modify a `mutable` member. - Commonly used for access counters, caches, or mutexes. ```cpp class Screen { public: void some_member() const { ++access_ctr; } private: mutable size_t access_ctr = 0; }; ``` ### 3. In-Class Initializer - When we provide an in-class initializer, we must do so following an `=` sign or inside `{}`. - While `int c(30);` is valid inside a function body, **inside a class definition C++ bans parentheses `()` for member initializers outright as a compile error** (even with literal arguments) to prevent parser ambiguity with member function declarations (see [Most Vexing Parse & In-Class Initializer]({{< relref "/programming/cpp/most-vexing-parse.md" >}})). ```cpp struct Widget { int a = 10; // ✅ Valid int b{20}; // ✅ Valid // int c(30); // ❌ Compile error: () syntax is prohibited outright for in-class member initializers int d(); // ⚠️ Compiles, but declares a MEMBER FUNCTION d(), not a data member! }; ``` ### 4. Functions That Return `*this` - A `const` member function that returns `*this` as a reference should have a return type that is a reference to `const` (`const CLASS&`). ```cpp class A { public: const A& display() const; }; ``` - Because `this` is `A *const` in a non-const member function and `const A *const` in a `const` member function, returning a reference from a `const` member function requires the return type to be `const A&`. --- ## 5. Class Scope Every class defines its own scope. Outside the class definition, member names must be accessed through an object (`.`), pointer (`->`), or the scope operator (`::`). ### Out-of-Line Member Definitions and Return Types When a member function is defined outside the class body, the parameter list and function body are inside class scope once the class name is seen (`CLASS::FUNC`). However, the **return type appears before the class name** and is therefore *outside* class scope: ```cpp class Window_mgr { public: using ScreenIndex = std::vector::size_type; ScreenIndex addScreen(const Screen&); }; // Return type appears before 'Window_mgr::' -> must qualify 'Window_mgr::ScreenIndex' Window_mgr::ScreenIndex Window_mgr::addScreen(const Screen &s) { /* ... */ } ``` ### Two-Phase Class Compilation & Name Lookup Classes are compiled in two distinct steps: 1. **Member declarations** are compiled first (types used in declarations must already be in scope). 2. **Member function bodies** are compiled only after the entire class definition has been processed (allowing member functions to reference any member declared later in the class). **Name Lookup Order inside Member Function Definitions:** 1. Search declarations inside the **member function's local block** (including parameters). 2. If not found, search declarations inside the **enclosing class scope** (all class members). 3. If not found, search declarations in the **outer scope(s)** before the member function definition. --- ## 6. Constructors ### 1. Constructor Initializer List - **Initialization vs. Assignment:** Data members are initialized *before* the constructor body (`{ ... }`) begins execution. Members omitted from the initializer list are default-initialized before entering the body, and assigning values inside the body is **assignment**, not initialization. - **Direct Member Constructor Invocation (`: MEMBER(ARGS...)`):** For example, in the `Screen` class below, writing `: contents(ht * wd, c)` in the constructor initializer list **directly invokes** the constructor of the `contents` member's type (`std::string`). Therefore, instead of constructing a temporary object as you would in an assignment (`contents = std::string(ht * wd, c);`), you simply pass the member constructor's arguments directly inside the parentheses. - **When Initializer List is Mandatory:** Members that are **`const`**, **references (`&`)**, or of a **class type without a default constructor** cannot be assigned to and **must** be initialized in the constructor initializer list. - **Order of Initialization:** Members are initialized **in the order in which they appear in the class definition**, NOT the order in the constructor initializer list. ```cpp class Screen { std::string contents; public: // 1. Initializer list (Recommended): Directly calls std::string(size_type, char) in a single step Screen(size_t ht, size_t wd, char c) : contents(ht * wd, c) {} // 2. Body assignment (Inefficient): First default-initializes contents to "", then creates a temporary std::string and assigns it // Screen(size_t ht, size_t wd, char c) { contents = std::string(ht * wd, c); } }; class X { int i; // Initialized 1st! int j; // Initialized 2nd! public: // Bug (UB): i is initialized first using uninitialized j! X(int val) : j(val), i(j) {} }; ``` ### 2. Delegating Constructors (C++11) - **Must Delegate in the Constructor Initializer List (`:`):** A delegating constructor must invoke another constructor of its own class inside the **constructor initializer list** after the colon (`:`). - **Pitfall: Never Call Another Constructor Inside the Constructor Body (`{ ... }`):** - Writing `Sales_data() { Sales_data("", 0, 0); }` inside `{ ... }` does **not** initialize the current object (`*this`). Instead, it creates an **unnamed temporary object (prvalue) inside the body scope that is immediately destroyed at the semicolon (`;`)**, leaving `*this`'s members default-initialized. - **Exclusive Delegation Rule:** If a constructor delegates to another constructor, its initializer list cannot initialize any other members simultaneously (e.g., `: Sales_data(), bookNo("x")` is illegal). Any additional work (such as reading from an input stream in `(4)` below) must be placed inside the constructor body `{ ... }`. ```cpp class Sales_data { public: // (1) Target constructor: initializes all data members directly Sales_data(std::string s, unsigned cnt, double price) : bookNo(s), units_sold(cnt), revenue(cnt * price) {} // (2) Correct delegating constructor: calls target constructor in the initializer list after ':' Sales_data() : Sales_data("", 0, 0) {} // (3) Wrong (Bug!): Calling inside '{ ... }' creates and destroys a temporary object without initializing *this // Sales_data() { Sales_data("", 0, 0); } // (4) Delegating + extra work: delegate in the initializer list, then run extra statements in '{ ... }' Sales_data(std::istream &is) : Sales_data() { double price = 0.0; is >> bookNo >> units_sold >> price; revenue = units_sold * price; } private: std::string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; ``` ### 3. Implicit Class-Type Conversions and `explicit` - **Converting Constructor:** Any constructor callable with a **single argument** defines an implicit conversion from that parameter type to the class type. - **One User-Defined Conversion Rule:** The compiler will automatically apply **only one** class-type conversion per expression. - **`explicit` Constructors:** - Prevents the constructor from being used for implicit conversions. - Specified **only on the declaration inside the class body** (not repeated on out-of-line definitions). - An `explicit` constructor can be used **only for direct initialization** (`CLASS a(val);`), NOT copy initialization (`CLASS a = val;` → compile error). ```cpp class Sales_data { public: explicit Sales_data(const std::string &s) : bookNo(s) {} private: std::string bookNo; }; std::string null_book = "9-999-99999-9"; Sales_data item1(null_book); // Valid: direct initialization // Sales_data item2 = null_book; // Compile error: copy initialization prohibited for explicit constructor ``` ### 4. Aggregate Classes and Literal Classes - **Aggregate Class:** A class with (1) all `public` data members, (2) no user-declared constructors, (3) no in-class initializers (C++11), and (4) no base classes or `virtual` functions. Can be initialized directly with braces (`Data d = { 0, "Anna" };`). - **Literal Class (`constexpr` Constructor):** A class whose objects can be evaluated at compile time. Must have literal-type data members, a trivial destructor, and at least one `constexpr` constructor (which initializes all data members and has an empty body `{}`). --- ## 7. `static` Class Members `static` members are associated with the **class as a whole**, rather than with individual objects of the class. ### Key Properties of `static` Members - **No `this` Pointer:** `static` member functions are not bound to any object; they **have no `this` pointer**, **cannot be declared as `const`**, and cannot access non-static members directly. - **Declaration vs. Definition (Why `static` Members Must Be Initialized Outside the Class):** - The `static` keyword appears **only on the declaration inside the class body**, never on the out-of-line definition. - **Why Out-of-Line Definition is Mandatory (Header `#include` & One Definition Rule, ODR):** - A non-static in-class initializer (`int val = 10;`) does not allocate memory; it is merely a blueprint telling constructors how to initialize future objects. By contrast, a `static` data member is an actual global-lifetime variable residing in a single memory location across the entire program. - Because class definitions live in header files (`.h`) that are `#include`d across multiple `.cc` translation units, defining and initializing a `static` member inside the class body would emit a duplicate definition in every `.o` object file, causing a linker **`multiple definition` error (ODR violation)**. - Therefore, C++ (prior to C++17) treats the **in-class declaration (`.h`)** like an `extern` declaration and requires the `static` member to be **defined and initialized exactly once in a single `.cc` file** outside the class (`double Account::interestRate = 0.05;`). - **Exception for Compile-Time Constants (`const` Integral / `constexpr`):** - `static const` integral types and `static constexpr` literal types do not require runtime constructor calls and can be directly substituted by the compiler (constant folding), so in-class initialization is permitted. - *(Note: Starting in C++17, `inline static double rate = 6.5;` allows in-class initialization of any `static` member by instructing the linker to merge duplicate definitions across translation units into one.)* ```cpp class Account { public: // static member functions can be defined inside or outside the class // In-class definitions are implicitly inline static double rate() { return interestRate; } static void rate(double newRate); private: static constexpr int period = 30; // In-class initializer allowed for constexpr static double interestRate; // Declaration inside class }; // Out-of-line definition: do not repeat the static keyword here double Account::interestRate = 0.05; void Account::rate(double newRate) { interestRate = newRate; } ``` ### Special Capabilities of `static` Members (vs. Non-Static Members) 1. **Incomplete Type Allowed:** A `static` data member can have the **same type as the class type of which it is a member** (an incomplete type inside the class body). Non-static data members can only be declared as pointers or references to their own class. 2. **Usable as Default Arguments:** A `static` data member can be used as a **default argument** for a member function because its value is independent of any object instance. ```cpp class Bar { public: Bar& clear(char = bkground); // Valid: static member used as default argument private: static Bar mem1; // Valid: static member can have incomplete type Bar *mem2; // Valid: pointer member can have incomplete type // Bar mem3; // Compile error: non-static data member must have complete type static const char bkground = ' '; }; ```