https://rentry.org/PPP2_p313

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

#include <iostream>

using std::cout;

// simple Date (control access)
class Date {
 public:
  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  month() { return m; }
  int  day() { return d; }
  int  year() { return y; }

 private:
  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{1970, 12, 30};  // OK
  // birthday.m = 14;              // error: Date::m is private

  cout << birthday.month() << '\n';  // we provided a way to read m
}

build & run:

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

PrevUpNext

Edit
Pub: 06 Apr 2023 14:39 UTC
Edit: 03 May 2023 01:06 UTC
Views: 325