default constructor

Example by: Ira Oldham, References: Savitch eighth edition, section 10.2; Gaddis seventh edition, section 13.7

We cannot directly initialize private data, but a constructor can initialize the data. We will look at a default constructor. Characteristics of constructors:

Additional characteristics of the default constructor:

1  class Date
2  {
3    int day;
4    int month;
5    int year;
6    bool validate(int day_parm, int month_parm, int year_parm);
7  public:
8    Date() {day=0; month=0; year=0;}
9    bool set_date(int day_parm, int month_parm, int year_parm);
10   void print_date();
11   int  get_day()   {return day;}
12   int  get_month() {return month;}
13   int  get_year()  {return year;}
14 };
15 int main(void)
16 {
17   Date today;
18   Date yesterday;
...
19     cout << "Date today: ";
20     today.print_date();
21     cout << "Date yesterday: ";
22     yesterday.print_date();
...
23 }
24 void Date::print_date()
25 {
26   if (day)
27     cout << month << '/' << day << '/' << year << endl;
28   else
29     cout << "The date has not been set\n";
30 }
Input date:
day:   31
month: 12
year:  1234
Date today: 12/31/1234
Date yesterday: The date has not been set

The default constructor automatically ran when the objects were created and set their member data to known values.