C++ gurus and learners, we program ourselves :P all work is CC licensed

Showing posts with label Date Class Operator Overloading. Show all posts
Showing posts with label Date Class Operator Overloading. Show all posts

Saturday, November 2

Date Class Question

A Question was posted:
Q. Write a definition of Date class that contains three private data member month, day and year that provides the following functionality

Creating date with default values (zero for day, month and year)
Setting value of date at the time of creation
Changing values (day, month or year separately or combine) of any date
Getting values (day, month or year separately ) of any date
Displaying date value
Keep track of how many dates are created in a program and a function to access this value
Comparing two dates
One date is less than other ( < )
One date is greater than other ( > )
Two dates are equal ( == )
Two dates are not equal ( != )
Increment 1 in day value of date ( ++ ) both pre and post
Decrement 1 in day value of date ( - - ) both pre and post
Here is my solution though it can be improved by using function calls instead of direct calls but works fine as well as function calls slow the code ;)

Code:
 
class Date
{
 int month, day, year;
public:
 static int DatesCreated;
 Date(int mm = 0, int dd = 0, int yyyy = 0)// :month(mm), day(dd), year(yyyy)
 {
  setDate(mm, dd, yyyy);
  DatesCreated++;
 }

 void setMonth(int mm)
 {
  month = mm;
 }

 void setDay(int dd)
 {
  day = dd;
 }

 void setYear(int yyyy)
 {
  year = yyyy;
 }

 void setDate(int mm = 0, int dd = 0, int yyyy = 0)
 {
  setMonth(mm);
  setDay(dd);
  setYear(yyyy);
 }

 int getMonth()
 {
  return month;
 }

 int getDay()
 {
  return day;
 }

 int getYear()
 {
  return year;
 }

 void displayDate()
 {
  cout << "Date is" << month << '/' << day << '/' << year << endl;
 }

 int getDatesCount()
 {
  return DatesCreated;
 }

 bool operator<(Date b)
 {
  if (year < b.year || month < b.month || day(Date b)
 {
  if (year > b.year || month > b.month || day>b.day)return true;
  return false;
 }

 bool operator==(Date b)
 {
  if (b.day == day && b.month == month && b.year == year)return true;
  return false;
 }

 bool operator!=(Date b)
 {
  if (b.day != day && b.month != month && b.year != year)return true;
  return false;
 }

 Date& operator++()
 {
  month = (month + 1) % 12;
  day = (day + 1) % 31;
  year = (year + 1) % 9999;
  return *this;
 }

 Date& operator--()
 {
  month = (12 + (month - 1)) % 12;
  day = (31 + day - 1) % 31;
  year = (9999 + year - 1) % 9999;
  return *this;
 }
};

int Date::DatesCreated = 0;

void main()
{
    //The code is self explaining :)
}