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>
using namespace std;
class Date {
private:
int day, month, year;
public:
Date(int d, int m, int y) {
day = d;
month = m;
year = y;
cout << day << '/' << month << '/' << year << '\n';
}
int getYear() { return year; }
friend int findAge(Date, Date);
};
int findAge(Date dob, Date today) {
return today.getYear() - dob.getYear();
}
int main() {
int d, m, y, db, mb, yb, age;
cout << "Write today's date in this format (d m y): ";
cin >> d >> m >> y;
cout << "Write date of birth in this format (d m y): ";
cin >> db >> mb >> yb;
Date today(d, m, y), dob(db, mb, yb);
age = findAge(dob, today);
cout << "The age is: " << age << '\n';
return 0;
}
Example:
Write today's date in this format (d m y): 16 7 2021
Write date of birth in this format (d m y): 7 3 2002
16/7/2021
7/3/2002
The age is: 19
Comments
Leave a comment