https://rentry.org/PPP2_p327

// Code derived from Stroustrup's PPP2 book
// § 9.7.3 Default constructors
//  -and beginning on p 327

#include <iostream>
#include <string>
#include <vector>

using namespace std;

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

// simple Date (use Month type):
class Date {
 public:
  Date(int yy, Month mm, int dd)  //
      : y{yy}, m{mm}, d{dd}
  {
    // initialize & check for valid date
    // ...
  }

  friend ostream& operator<<(ostream& os, const Date& d)
  {
    return os << '{' << d.y << ',' << int(d.m) << ',' << d.d << '}';
  }

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

int main()
{
  // Date d0;                    // error: no initializer
  // Date d1{};                  // error: empty initializer
  // Date d2{1998};              // error: too few arguments
  // Date d3{1, 2, 3, 4};        // error: too many arguments
  // Date d4{1, "jan", 2};       // error: wrong argument type
  Date d5{1, Month::jan, 2};  // OK: use the three-argument constructor

  [[maybe_unused]] Date d6{d5};  // OK: use the copy constructor

  {
    string         s1 = string{};  // default value: the empty string " "
    vector<string> v1 = vector<string>{};  // default value: the empty vector;
                                           // no elements
  }

  {
    // However, we prefer the equivalent and colloquial:
    string         s1;  // default value: the empty string " "
    vector<string> v1;  // default value: the empty vector; no elements
  }

  // exposition only
  /*
  {
    // Imagine that we could have an uninitialized string or vector.
    string s;

    // oops: loop an undefined number of times
    for (int i = 0; i < (int)s.size(); ++i)
      s[i] = toupper(s[i]);  // oops: read and write a random memory location

    vector<string> v;
    v.push_back("bad");  // oops: write to random address

    // we could insist on an initializer and then write
    //  (but we don’t think [this is] particularly pretty)
    string         s1 = "";
    vector<string> v1{};
  }
  */
}

build & run:

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

PrevUpNext

Edit
Pub: 06 Apr 2023 17:47 UTC
Edit: 03 May 2023 01:17 UTC
Views: 429