https://rentry.org/PPP2_p314

// Code derived from Stroustrup's PPP2 book
// § 9.4.4 Defining member functions
//  -and beginning on p 314

// simple Date (some people prefer implementation details last)
class Date {
 public:
  // constructor: check for valid date and initialize
  Date(int y, int m, int d);

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

  int month() { return m; }

  // ...

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

Date::Date(int yy, int mm, int dd)  // constructor
    : y{yy}, m{mm}, d{dd}           // note: member initializers
{
}

void Date::add_day(int n)
{
  // ...
}

//------------------------------------------------------------------------------

int month()  // oops: we forgot Date::
{
  return m;  // not the member function, can’t access m
}

//------------------------------------------------------------------------------

int main()
{
  {
    int x;  // first define the variable x

    // ...

    x = 2;  // later assign to x
  }

  {
    [[maybe_unused]] int x{2};  // define and immediately initialize with 2
  }

  Date sunday{2004, 8, 29};  // initialize sunday with {2004, 8, 29}
  sunday.add_day(7);         // skip 7 days
  return sunday.month();     // get sunday's month
}

build & run:

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

PrevUpNext

Edit
Pub: 06 Apr 2023 14:42 UTC
Edit: 03 May 2023 01:08 UTC
Views: 359