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/
# Object-Oriented Programming (OOP)
Based on *C++ Primer, 5th ed.*, Chapter 15: Object-Oriented Programming and Section 19.2.1: `dynamic_cast`, this post summarizes the three pillars of OOP, **Upcast / Downcast, Object Slicing, and Polymorphic Containers**, **Virtual Functions** (`virtual`, `override`, `final`), **Pure Virtual Functions** (`= 0`) and **Abstract Base Classes**, and access control under inheritance.
## 1. The Three Pillars of OOP
Object-oriented programming is built on three core principles:
- **Data Abstraction:** Define classes that separate interface from implementation. — see [Classes]({{< relref "/programming/cpp/primer/classes.md" >}})
- **Inheritance:** Define classes that model the relationships among similar types.
- **Dynamic Binding:** Use objects of derived types while ignoring the details of how they differ.
---
## 2. Upcast vs. Downcast and Static vs. Dynamic Type
Expressions dealing with polymorphic types distinguish between two types:
- **Static Type:** The type of a variable or expression **known at compile time** from its declaration — e.g., a `Base*` pointer variable always has static type `Base*`.
- **Dynamic Type:** The type of the actual object in memory that a pointer or reference **denotes at runtime** — e.g., if a `Base*` pointer points to a `Derived` object, its dynamic type is `Derived`.
- For a **value object variable** (neither pointer nor reference), its static type and dynamic type are always identical.
### 1. Upcast (Base ← Derived) vs. Downcast (Derived ← Base)
| Direction | Target Form | Conversion Method & Validity | Dynamic Type & Runtime Behavior |
| :--- | :--- | :--- | :--- |
| **Upcast**
Base ← Derived | **Pointer / Reference**
`Base*`, `Base&` | ✅ Implicit conversion | **Preserves Dynamic Type `Derived`**
Dynamic binding invokes `Derived`'s overridden `virtual` functions. |
| **Upcast**
Base ← Derived | **Object — by value**
`Base` | ⚠️ Valid syntax, but **invokes `Base` copy constructor only** | **Object Slicing occurs**
`Derived` members and dynamic type info are sliced off, leaving a plain `Base` object. |
| **Downcast**
Derived ← Base | **Pointer / Reference**
`dynamic_cast(BASE_PTR)`
`dynamic_cast(BASE_REF)` | ✅ Use **`dynamic_cast`** when `Base` has at least one `virtual` function — compile error without a `virtual` function | Verifies at runtime via RTTI whether the target is `Derived`:- Success: returns `Derived*` / `Derived&`
- Pointer failure: returns `nullptr`
- Reference failure: since a reference cannot be null, throws `std::bad_cast`
|
| **Downcast**
Derived ← Base | **Object — by value**
`Derived` | ❌ Compile error | A `Base` object does not contain `Derived` member storage, so value-object downcasting is impossible. |
- **Why Does `dynamic_cast` Require at Least One `virtual` Function? — `vptr` / `vtable` and RTTI (Run-Time Type Identification):**
- **Non-polymorphic class without `virtual`:** Under C++'s Zero-Overhead principle, only data members are laid out in memory with no hidden object header — at runtime, no type tag exists in memory at all.
- **Polymorphic class with at least one `virtual` function:** The compiler inserts a hidden pointer **`vptr`** at the start of each object, pointing to a shared **`vtable`** that stores both virtual function addresses and **RTTI metadata** (`std::type_info` and inheritance graph info).
- Because `dynamic_cast` traverses **`vptr` → `vtable` → RTTI** at runtime to verify the dynamic type, attempting `dynamic_cast` on a class without `virtual` functions is a compile error.
```cpp
#include
#include // std::bad_cast
class Base {
public:
virtual ~Base() = default;
virtual void speak() const { std::cout << "Base\n"; }
};
class Derived : public Base {
public:
int extra_data = 42;
void speak() const override { std::cout << "Derived\n"; }
};
void cast_examples() {
Derived d;
// 1. Upcast (Pointer / Reference): Implicit conversion + preserves Dynamic Type + Dynamic Binding works!
Base *bp = &d;
Base &br = d;
bp->speak(); // Prints "Derived" (Dynamic Binding)
br.speak(); // Prints "Derived" (Dynamic Binding)
// 2. Upcast (Object): "Slice Down" (Object Slicing) -> loses Dynamic Type info!
Base sliced = d; // Derived::extra_data is sliced off; only Base subobject is copied
sliced.speak(); // Prints "Base" (sliced is purely a Base object)
// 3. Downcast (Pointer): dynamic_cast -> returns nullptr on failure
if (Derived *dp = dynamic_cast(bp)) {
std::cout << dp->extra_data << "\n"; // Succeeds: bp actually points to Derived(d)
}
Base plain_base;
Base *bp2 = &plain_base;
Derived *dp_fail = dynamic_cast(bp2); // Fails! dp_fail == nullptr
// 4. Downcast (Reference): dynamic_cast -> throws std::bad_cast on failure
try {
Derived &dr_fail = dynamic_cast(*bp2);
} catch (const std::bad_cast &e) {
std::cout << "Downcast failed: " << e.what() << "\n";
}
// 5. Downcast (Object): Impossible!
// Derived d2 = plain_base; // Compile error!
}
```
### 2. Scope of `dynamic_cast`
1. **Downcast (`Derived*` ← `Base*`, `Derived&` ← `Base&`):** The most common use. Pointer casts return `nullptr` on failure; reference casts throw `std::bad_cast`.
2. **Crosscast (`BaseB*` ← `BaseA*`):** Under multiple inheritance, converts **across two unrelated co-inherited `Base` classes** of the same derived object — impossible with `static_cast`, and resolved at runtime via RTTI.
3. **`dynamic_cast(BASE_PTR)`:** Obtains the **starting memory address of the most-derived object**, regardless of which `Base*` subobject pointer you currently hold.
4. **Upcast (`Base*` ← `Derived*`):** Syntactically allowed, but resolved at compile time identically to an implicit conversion and unnecessary in practice.
```cpp
// Crosscast and dynamic_cast under multiple inheritance (across co-inherited bases: Serializable* <- Printable*)
class Printable { public: virtual ~Printable() = default; };
class Serializable { public: virtual ~Serializable() = default; };
class Document : public Printable, public Serializable {};
Printable *p = new Document();
// Printable and Serializable have no parent-child relationship, yet succeed because *p is a Document!
if (Serializable *s = dynamic_cast(p)) {
// Obtains pointer to Document's Serializable subobject
void *most_derived = dynamic_cast(s); // Returns starting address of the full Document object
}
delete p;
```
### 3. Store Pointers to Use Dynamic Binding in Containers
- **Storing by value causes Object Slicing (`std::vector`):** Although storing into a concrete `Base` value container is syntactically legal, inserting a `Derived` object causes **Object Slicing**, stripping away the `Derived` part so Dynamic Binding does not work.
- **No direct reference containers (`std::vector` — compile error):**
- **Language rule:** References are aliases rather than objects, so C++ forbids arrays of references (`Base&[]`) and pointers to references (`Base&*`, required internally by container allocators).
- **Container operation constraints:** Reallocation and element shifts during `insert` / `erase` require rebinding slots to different targets and default-constructing slots on `resize`, whereas references cannot be rebound after initialization or default-constructed. Use `std::vector>` — a copyable, rebindable pointer wrapper — when reference semantics are desired.
- **Pointer choice by ownership:** Indirection through either smart pointers or raw pointers equally preserves Dynamic Type and Dynamic Binding.
- **Owning container (heap-allocated objects):** Use **`std::vector>`** or **`std::vector>`** for automatic cleanup on destruction or exceptions.
- **Non-owning observer container:** Use **`std::vector`** when merely referencing objects whose lifetimes are already managed elsewhere, such as on the stack or in another owner container.
---
## 3. Essential Design Rules for Base and Derived Classes
### 1. Base Classes Must Define a `virtual` Destructor (`virtual ~Base()`)
- When deleting a dynamically allocated derived object through a base pointer (`Base *p = new Derived(); delete p;`), **if `~Base()` is not `virtual`, the compiler uses the static type (`Base*`) and runs only `~Base()`, leaking `Derived`'s resources and causing Undefined Behavior**.
- Therefore, every root base class in an inheritance hierarchy must define a **`virtual` destructor (`virtual ~Base()`)**.
### 2. Derived Constructors Initialize Base Subobjects via the Base Constructor
- A derived constructor **cannot directly initialize base-class data members** in its member initializer list. Instead, it **must invoke the base-class constructor** to initialize its base subobject first.
- **Construction Order:** `Base` constructor runs first → `Derived` members and constructor body run second.
- **Destruction Order — Reverse of Construction:** `~Derived()` runs first → `~Base()` runs second.
```cpp
class Quote {
public:
Quote() = default;
Quote(const std::string &book, double sales_price)
: bookNo(book), price(sales_price) {}
std::string isbn() const { return bookNo; }
virtual double net_price(std::size_t n) const { return n * price; }
virtual ~Quote() = default; // Essential! Virtual destructor for polymorphic deletion
private:
std::string bookNo;
protected:
double price = 0.0; // Accessible to derived classes
};
class Bulk_quote : public Quote {
public:
Bulk_quote() = default;
// Delegate initialization of base members (bookNo, price) to the Quote constructor!
Bulk_quote(const std::string &book, double p, std::size_t qty, double disc)
: Quote(book, p), min_qty(qty), discount(disc) {}
double net_price(std::size_t cnt) const override {
if (cnt >= min_qty) return cnt * (1 - discount) * price;
return cnt * price;
}
private:
std::size_t min_qty = 0;
double discount = 0.0;
};
```
---
## 4. Virtual Functions and Abstract Base Class Rules
For a summary table of the `virtual`, `= 0` (pure virtual), `override`, and `final` keywords, see **[C++ Keywords Reference: Inheritance & Polymorphism (OOP) Keywords]({{< relref "/programming/cpp/keywords.md#2-inheritance--polymorphism-oop-keywords-virtual--0-override-final" >}})**.
### 1. `virtual` & `override` keyword
1. **Conditions for Dynamic Binding & Name Hiding When `virtual` Is Omitted:**
- The called member function must be declared **`virtual`**, and the call must be made through a **pointer or reference**. Calling on a value object resolves statically at compile time.
- If a base member function is **not** declared `virtual`, defining a same-named function in `Derived` does **not** override it, and adding `override` is a compile error; it merely performs **Name Hiding**. Calling it through a `Base*` pointer resolves statically to the `Base` version regardless of the runtime object type:
```cpp
class Base {
public:
virtual ~Base() = default;
void non_virt() const { std::cout << "Base::non_virt\n"; } // NOT virtual
virtual void virt() const { std::cout << "Base::virt\n"; } // virtual
};
class Derived : public Base {
public:
// void non_virt() const override {} // ❌ Compile error! Base function is not virtual
void non_virt() const { std::cout << "Derived::non_virt\n"; } // ⚠️ Name Hiding, NOT overriding
void virt() const override { std::cout << "Derived::virt\n"; } // ✅ Valid override
};
void binding_demo() {
Derived d;
Base *ptr = &d; // Dynamic Type is Derived, while the pointer's Static Type is Base*
ptr->non_virt(); // 💥 Prints "Base::non_virt"! (Non-virtual: follows Static Type Base*)
ptr->virt(); // ✅ Prints "Derived::virt"! (Dynamic Binding)
}
```
2. **What Happens When `override` Is Omitted:**
- **When the signature matches exactly:** Once a function is declared `virtual` in `Base`, it remains `virtual` in derived classes even if both `virtual` and `override` are omitted, so overriding still takes effect. However, if the `Base` signature is later modified, the compiler will not catch the mismatch.
- **When parameter types or `const` qualifiers differ:** Without `override`, a signature mismatch **compiles silently without error** and declares a **separate new function + Name Hiding** instead of overriding. Calls through `Base*` or `Base&` then unexpectedly invoke the **`Base` version** at runtime — always mark every intended override with `override` so mismatches become immediate compile errors:
```cpp
class Base {
public:
virtual ~Base() = default;
virtual void process(int x) const { std::cout << "Base::process\n"; }
};
class Derived : public Base {
public:
// 1) Exact signature match still overrides even without 'override' (discouraged)
// void process(int x) const { std::cout << "Derived::process\n"; }
// 2) Accidentally omitted 'const' AND omitted 'override':
void process(int x) { std::cout << "Derived::process\n"; } // ⚠️ Compiles silently as a separate function + Name Hiding!
// void process(int x) override; // ❌ With 'override', the missing 'const' is caught immediately at compile time!
};
void override_pitfall() {
Derived d;
const Base &br = d;
br.process(10); // 💥 Prints "Base::process"! Derived::process did not override due to missing const
}
```
### 2. Virtual Functions and Default Arguments Pitfall
- When a virtual function call uses a default argument, the value is determined at compile time by the **static type** of the pointer or reference, not the dynamic type. Always give base and derived overrides identical default arguments.
### 3. Circumventing the Virtual Mechanism (`BASE::FUNC()`)
- When a derived virtual function needs to call its base-class version, it must qualify the call with the scope operator: **`BASE::FUNC(ARGS...)`**. Omitting `BASE::` causes dynamic binding to resolve back to the derived function itself, resulting in **infinite recursion**.
---
## 5. Access Control Under Inheritance (`protected`, `private`, `friend`)
For the `public`, `protected`, and `private` access table and derivation access specifier rules, see **[Classes: Access Control]({{< relref "/programming/cpp/primer/classes.md#3-access-control-access-specifiers" >}})**.
### 1. `protected` Access Specifier
- The purpose of `protected` is to keep members hidden like `private` from external users while **opening access to derived classes**. Meanwhile, `friend` always operates at the same access level as the member functions of whichever class declared that `friend`.
- **Important Restriction:** `Derived` may access the base class's `protected` members **only through the `Base` subobject embedded inside a `Derived` object**. As shown below, it has no special access to `protected` members of an independent standalone `Base` object:
```cpp
class Base {
protected:
int prot_mem = 0;
};
class Derived : public Base {
void test(Derived &d, Base &b) {
d.prot_mem = 10; // ✅ OK: accessed through the Base subobject inside Derived object d
// b.prot_mem = 20; // ❌ Compile error: cannot access protected member on standalone Base object b!
}
};
```
### 2. `private` Access Specifier
- **Present in memory:** Every `Derived` object still physically contains the `Base` class's `private` data members inside its embedded `Base` subobject.
- **No direct access:** Even inside `Derived`'s own member functions, `Base`'s `private` members cannot be read or modified directly by name; they must be initialized and manipulated indirectly **through `Base`'s constructors and `public` / `protected` member functions**.
### 3. Friendship Is Not Inherited (`friend`)
- Friends of a base class have no special access to members of its derived classes, and derived classes have no special access to classes that grant friendship to the base class.