https://rentry.org/PPP2_p312

// Code derived from Stroustrup's PPP2 book
// § 9.4.3 Keep details private
//  -and beginning on p 312

// simple Date:
// guarantee initialization with constructor
// provide some notational convenience
struct Date {
  Date(int y, int m, int d);  // check for valid date and initialize

  void add_day(int n);  // increase the Date by n days

  int y, m, d;  // year, month, day
};

Date::Date(int y, int m, int d) : y{y}, m{m}, d{d} {}

int main()
{
  Date birthday{1960, 12, 31};  // December 31, 1960
  ++birthday.d;                 // ouch! Invalid date
                                // (birthday.d==32 makes birthday invalid)

  Date today{1970, 2, 3};
  today.m = 14;  // ouch! Invalid date (today.m==14 makes today invalid)
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_09/main_p312.cpp && ./a.out

PrevUpNext

Edit
Pub: 06 Apr 2023 14:37 UTC
Edit: 03 May 2023 01:05 UTC
Views: 608