bhylu.com

Advertisements

C++ Composition

Represent a route window inside a delivery rather than flattening unrelated fields or inheriting for reuse.

How it works

Composition means one object contains or owns another useful object. A delivery has a time window; it is not a kind of time window. This relationship is clearer as a member than as inheritance. Small value types can be copied, tested and formatted independently. Decide which type validates a cross-field rule, such as a window ending after it starts, and enforce it at the boundary where that combination is constructed.

Run it locally

Use a C++20 compiler and matching standard library in a separate lab folder. The command uses c++; substitute g++, clang++ or zig c++ for your toolchain. C++ does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

c++ -std=c++20 -Wall -Wextra -Wpedantic -Werror composition.cpp -o lesson

On Windows use -o lesson.exe and run .\lesson.exe in PowerShell. On Unix-like systems run ./lesson. Thread examples may need -pthread on your platform.

Download the complete C++ source. Run file labs in a private empty directory, away from existing reports.

Example

C++20 · composition.cpp

#include <iostream>
#include <string>

struct Window { int begin_hour; int end_hour; };
struct Delivery { std::string stop; Window window; int parcels; };

int main() {
    Delivery delivery{"Quay", {9, 11}, 4};
    if (delivery.window.begin_hour >= delivery.window.end_hour) { return 1; }
    std::cout << delivery.stop << ": " << delivery.window.begin_hour << "-" << delivery.window.end_hour << ", " << delivery.parcels << " parcels\n";
}

Expected result

Quay: 9-11, 4 parcels

The nested member keeps the time-window concept visible. The simple aggregate relies on caller validation in this fixture; a public scheduling module should promote the window to a checked type if invalid windows must never exist. The string and nested values copy normally, so the object has no manual resource-management burden.

Consult the WG21 C++ working group and the C++ Core Guidelines for language references and design guidance. Check the selected standard version and your implementation’s library support.