> For the complete documentation index, see [llms.txt](https://nodejsdocs.gitbook.io/everthing-c++/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://nodejsdocs.gitbook.io/everthing-c++/classes-structs-and-enums-deep-dive-for-performance-critical-systems.md).

# Classes, Structs, and Enums — Deep Dive for Performance-Critical Systems

This chapter sharpens your grasp on object modeling and type design in C++ with a lens toward high-performance and latency-sensitive systems. While the basics are covered, our focus is on minimizing runtime costs, improving cache friendliness, and enabling compile-time guarantees.

***

### 1. Classes, Structs, and Access Specifiers

#### 1.1 What is a Class?

A **class** encapsulates data and functions that define an object. It enables **encapsulation**, **data hiding**, and **object-oriented modeling**. In performance-critical systems, managing **object layout**, **memory alignment**, and avoiding **runtime overhead** are key goals.

```cpp
class Order {
public:
    void submit();
private:
    double price;
    int quantity;
};
```

🔸 Use `final` to avoid subclassing, and avoid virtual methods unless truly necessary to reduce indirection.

#### 1.2 What is a Struct?

A **struct** is almost identical to a class but defaults members to `public`. Ideal for plain data objects (PODs) or shared memory structures.

```cpp
struct OrderID {
    int id;
    long timestamp;
};
```

🔸 Useful for binary-compatible formats, shared memory messages, or data passed over sockets.

#### 1.3 Access Specifiers

* `public`: Accessible from anywhere — used for interfaces.
* `private`: Hidden implementation details.
* `protected`: Allows access from derived classes — rarely needed in flat design.

***

### 2. Inheritance and Interfaces

#### 2.1 Single Inheritance

Used to share functionality. Try to use **static polymorphism** (via templates) when performance matters.

```cpp
class Instrument {
public:
    double get_price() const;
};
```

#### 2.2 Multiple Inheritance

Should be avoided due to:

* VTable overhead
* Ambiguity in base members
* Harder layout for CPU prefetching

🔸 Replace with **composition**:

```cpp
class Logger { void log(); };
class FileWriter { void write(); };
class App : public Logger, public FileWriter {}; // ❌ Risky

class App {
    Logger logger;
    FileWriter writer;
}; // ✅ Better
```

#### 2.3 Abstract Classes and Interfaces

Virtual functions cost extra indirection. Use them only if dynamic dispatch is truly necessary.

```cpp
class RiskChecker {
public:
    virtual bool check(double px, int qty) = 0;
    virtual ~RiskChecker() = default;
};
```

🔸 Costs \~1-2 cycles, and adds \~20 cycles if branch mispredicted. Replace with CRTP where possible.

***

### 3. Constructors

#### 3.1 Default Constructor

Called when object is created without arguments. Use `explicit` to avoid implicit conversions.

```cpp
struct Order {
    double price;
    int quantity;
    Order() = default; // Default constructor
};
```

#### 3.2 Custom Constructors

Use initializer lists for better performance and clarity.

```cpp
Order(double p, int q) : price(p), quantity(q) {}
```

***

### 4. Destructors

* Implicitly called when object goes out of scope.
* Use `virtual` only when needed for polymorphism.
* Use `= default` if no special logic is needed.

```cpp
~Order() = default; // Compiler optimized
```

***

### 5. Aggregate Initialization

Useful for bulk POD-type initialization.

```cpp
struct MarketSnapshot {
    double bid, ask;
};
MarketSnapshot snap = {100.25, 100.30};
```

🔸 No constructor overhead — good for memory-mapped or network-aligned data.

***

### 6. Structured Binding (C++17)

Unpacks multiple members elegantly.

```cpp
OrderID id = {42, 1698203940};
auto [idNum, ts] = id;
```

🔸 Watch for unnecessary copies. Use `const&` if needed:

```cpp
auto& [idNumRef, tsRef] = id;
```

***

### 7. Enums

#### 7.1 Traditional Enums

```cpp
enum Side { Buy, Sell };
```

🔸 Weak typing — can be implicitly converted to `int`. Risky.

#### 7.2 Scoped Enums (enum class)

```cpp
enum class Side : uint8_t { Buy, Sell };
```

🔸 Stronger typing, better for binary protocols or serialization.

***

### 8. Tricky Performance-Level Questions with Examples

* **Q: Why prefer structs over classes in packet/message definitions?**\
  **A:** Structs default to public access, avoid vtables, and enable memory predictability.
* **Q: Why avoid virtual destructors in hot objects?**\
  **A:** They introduce vtable overhead, increase branch misprediction risk, and cause more cache misses.
* **Q: Can inheritance harm performance?**\
  **A:** Yes. Layout becomes non-trivial. Polymorphism adds runtime indirection.
* **Q: Should I use CRTP instead of virtual functions?**\
  **A:** Yes. Example:

```cpp
template <typename Derived>
class RiskCheckerBase {
public:
    bool check(double px, int qty) {
        return static_cast<Derived*>(this)->check_impl(px, qty);
    }
};

class MyChecker : public RiskCheckerBase<MyChecker> {
public:
    bool check_impl(double px, int qty) { return px > 100 && qty < 1000; }
};
```

* **Q: Alternatives to runtime polymorphism?**\
  **A:** `std::variant`, `std::function`, tag-dispatching, and template specialization.

***

Next: Chapter 10 — Memory Layout, Stack vs Heap, and Performance Patterns
