Create a class Date whose object can store a day, month and year. Include the necessary
constructors to initialize the objects and function to display the date in ‘dd/mm/yyyy’ format.
Define a non-member function findAge(Date dob, Date today) which should return the calculated
age from the input dates ‘dob’ and ‘today’. Set this function as friend to Date class. Write a main
function to read the today’s date and date of birth of a person from the user and display the age
of that person by calling the proper function.
#include <iostream>
#include <string>
using namespace std;
class Date{
private:
//object can store a day, month and year.
int day;
int month;
int year;
public:
//constructors to initialize the objects
Date(int day,int month,int year){
this->day=day;
this->month=month;
this->year=year;
}
//function to display the date in ‘dd/mm/yyyy’ format.
void display(){
cout<<this->day<<"/"<<this->month<<"/"<<this->year;
}
int getDay(){
return day;
}
int getMonth(){
return month;
}
int getYear(){
return year;
}
//Set this function as friend to Date class.
friend Date findAge(Date dob, Date today);
};
//Define a non-member function findAge(Date dob, Date today) which should return the calculated
//age from the input dates ‘dob’ and ‘today’.
Date findAge(Date dob, Date today){
//aray of days in months
int month[] = { 31, 28, 31, 30, 31, 30, 31,
31, 30, 31, 30, 31 };
if (dob.day > today.day) {
today.day+= month[dob.month - 1];
today.month--;
}
if (dob.month > today.month) {
today.year--;
today.month += 12;
}
//calculate age
int ageDays = today.day - dob.day;
int ageMonths = today.month - dob.month;
int ageYears =today.year - dob.year;
return Date(ageDays,ageMonths,ageYears);
}
//Write a main function to read the today’s date and date of birth of a
//person from the user and display the age of that person by calling the proper function.
int main () {
int dayNow;
int monthNow;
int yearNow;
int personBirthDay;
int personBirthMonth;
int personBirthYear;
//get today's date
cout<<"Enter today's date: ";
cin>>dayNow>>monthNow>>yearNow;
Date todayDate(dayNow,monthNow,yearNow);
//get the person birthdate
cout<<"Enter the person birthdate: ";
cin>>personBirthDay>>personBirthMonth>>personBirthYear;
Date personBirthDate(personBirthDay,personBirthMonth,personBirthYear);
cout<<"\nToday's date: ";
todayDate.display();
cout<<"\nThe person birthdate: ";
personBirthDate.display();
Date ageDate=findAge(personBirthDate,todayDate);
//display age
cout<<"\nThe age of the person is: "<<ageDate.getYear()<<" year(s), "<<ageDate.getMonth()<<" month(s),"<<ageDate.getDay()<<" day(s).\n\n";
//Delay
system("pause");
return 0;
}
Comments
Leave a comment