https://rentry.org/PPP2_p330

// Code derived from Stroustrup's PPP2 book
// § 9.7.4 const member functions
//  -and beginning on p 330

#include <iostream>

using namespace std;

enum class Month {
  jan = 1,
  feb,
  mar,
  apr,
  may,
  jun,
  jul,
  aug,
  sep,
  oct,
  nov,
  dec
};

class Date {
 public:
  Date(int yy, Month mm, int dd) : y{yy}, m{mm}, d{dd} {}

  // . . .

  int   day() const;    // const member: can’t modify the object
  Month month() const;  // const member: can’t modify the object
  int   year() const;   // const member: can’t modify the object

  void add_day(int n);    // non-const member: can modify the object
  void add_month(int n);  // non-const member: can modify the object
  void add_year(int n);   // non-const member: can modify the object

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

int Date::day() const
{
  // ++d;  // error: attempt to change object from const member function

  return d;
}

// naive
void Date::add_day(int n) { d += n; }

void some_function(Date& d, const Date& start_of_term)
{
  [[maybe_unused]] int a = d.day();              // OK
  [[maybe_unused]] int b = start_of_term.day();  // should be OK (why?)
  d.add_day(3);                                  // fine

  // start_of_term.add_day(3);     // error
}

int main()
{
  Date       d{2000, Month::jan, 20};
  const Date cd{2001, Month::feb, 21};

  cout << d.day() << " — " << cd.day() << '\n';  // OK
  d.add_day(1);                                  // OK

  // cd.add_day(1);  // error: cd is a const
}

build & run:

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

PrevUpNext

Edit
Pub: 06 Apr 2023 17:55 UTC
Edit: 03 May 2023 01:22 UTC
Views: 588