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:
-
Constructors are member functions in a class.
-
Constructors are normally public.
-
The name of a constructor is exactly the same as the name of the class.
-
Constructors should initialize all the data members of the object.
The constructors should guarentee that the initial values are all set
properly. All mutator methods should make sure the new values
they set are all properly set. Then there is never junk in any member data.
-
Constructors do not have a return type, not even void.
-
A constructor automatically runs when an object is created.
They are not be called, as ordinary functions are called.
Additional characteristics of the default constructor:
-
A default constructor has no parameters.
-
A default constructor runs when no arguments are supplied.
-
Always code a default constructor for every class.
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
-
line 8 The default constructor.
It sets 0 to the member data, which is an indication that the date
has not been set. The data is not a valid date, but is not junk.
-
lines 16-17 Two objects are created. The default constructor
runs automatically, and sets the values of their member data.
-
lines between 18 and 19 are not shown. They set the value of
the object: today. So, today has a real date, but yesterday
has not had its date set so that it still only contains 0 values.
-
lines 19-21 print the today and yesterday.
-
lines 24-30 The print_data method has been modified so that
the date is printed, unless the values are 0.
If the values are 0, it prints: The date has not been set
The default constructor automatically ran when the objects
were created and set their member data to known values.