#include <iostream.h>
#include <string.h>
class Date {
public:
Date( int = 1, int = 1, int = 1900 );
void print() const;
~Date();
private:
int month; // 1-12 (January-December)
int day; // 1-31 based on month
int year; // any year
int checkDay( int ) const;
};
Date::Date( int mn, int dy, int yr )
{
if ( mn > 0 && mn <= 12 )
month = mn;
else {
month = 1;
cout << "Month " << mn
<< " invalid. Set to month 1.\n";
}
year = yr;
day = checkDay( dy );
cout << "Date object constructor for date ";
print();
cout << endl;
}
void Date::print() const
{
cout << month << '/' << day << '/' << year;
}
Date::~Date()
{
cout << "Date object destructor for date ";
print();
cout << endl;
}
int Date::checkDay( int testDay ) const
{
static const int daysPerMonth[ 13 ] =
{ 0,31,28,31,30,31,30,31,31,30,31,30,31 };
if ( testDay > 0 && testDay <= daysPerMonth[ month ] )
return testDay;
if ( month == 2 && testDay == 29 &&
( year % 400 == 0 ||
( year % 4 == 0 && year % 100 != 0 ) ) )
return testDay;
cout << "Day " << testDay
<< " invalid. Set to day 1.\n";
return 1;
}
class Employee {
public:
Employee(const char *, const char *,
const Date &, const Date & );
void print() const;
~Employee();
private:
char firstName[ 25 ];
char lastName[ 25 ];
const Date birthDate; //composition: member object
const Date hireDate; //composition: member object
};
Employee::Employee(const char *first, const char *last,
const Date &dateOfBirth, const Date &dateOfHire )
: birthDate( dateOfBirth ),
hireDate( dateOfHire )
{
int length = strlen( first );
length = ( length < 25 ? length : 24 );
strncpy( firstName, first, length );
firstName[ length ] = '\0';
length = strlen( last );
length = ( length < 25 ? length : 24 );
strncpy( lastName, last, length );
lastName[ length ] = '\0';
cout << "Employee object constructor: "
<< firstName << ' ' << lastName << endl;
}
void Employee::print() const
{
cout << lastName << ", " << firstName << "\nHired: ";
hireDate.print();
cout << " Birth date: ";
birthDate.print();
cout << endl;
}
Employee::~Employee()
{
cout << "Employee object destructor: "
<< lastName << ", " << firstName << endl;
}
int main()
{
Date birth( 7, 24, 1949 );
Date hire( 3, 12, 1988 );
Employee manager( "Bob", "Jones", birth, hire );
cout << '\n';
manager.print();
cout << "\nTest Date constructor "
<<"with invalid values:\n";
Date lastDayOff(14,35,1994); //invalid month and day
cout << endl;
return 0;
}
Date object constructor for date 7/24/1949
Date object constructor for date 3/12/1988
Employee object constructor: Bob Jones
Jones, Bob
Hired: 3/12/1988 Birth date: 7/24/1949
Test Date constructor with invalid values:
Month 14 invalid. Set to month 1.
Day 35 invalid. Set to day 1.
Date object constructor for date 1/1/1994
Date object destructor for date 1/1/1994
Employee object destructor: Jones, Bob
Date object destructor for date 3/12/1988
Date object destructor for date 7/24/1949
Date object destructor for date 3/12/1988
Date object destructor for date 7/24/1949