Programs & Examples
Classes and Objects · Study material
A Time class that always stays valid
Storing a single number of seconds and normalising it in one private helper means hours, minutes and seconds can never become invalid – adding or subtracting simply wraps around midnight.
#include <format>
#include <iostream>
#include <string>
class Time {
int total_; // seconds since midnight, always 0..86399
static int wrap(long long s) { return static_cast<int>(((s % 86400) + 86400) % 86400); }
public:
Time(int h = 0, int m = 0, int s = 0) : total_(wrap(h * 3600LL + m * 60 + s)) {}
Time add(int seconds) const { Time t; t.total_ = wrap(total_ + static_cast<long long>(seconds)); return t; }
std::string str() const { return std::format("{:02}:{:02}:{:02}", total_ / 3600, total_ / 60 % 60, total_ % 60); }
};
int main() {
Time start(23, 45, 30);
std::cout << start.str() << " + 20 min = " << start.add(20 * 60).str() << '\n';
std::cout << Time(0, 0, 5).str() << " - 10 s = " << Time(0, 0, 5).add(-10).str() << '\n';
return 0;
}
23:45:30 + 20 min = 00:05:30 00:00:05 - 10 s = 23:59:55
A Product class with members defined outside
The Product example in the introduction shows the inside/outside split, a validating setter and default member initializers working together.
Sorting objects with defaulted comparisons
The Version struct above becomes sortable with one line, auto operator<=>(const Version&) const = default;, because std::sort uses operator<.