Answer to Question #229113 in C++ for Karthi

Question #229113
Create a class DATE to read the date and overload ++ (both prefix
and postfix) to generate the next date.
For Example, if d = 15/8/2019 output d++ or ++d should return
16/8/2019. Consider all possible test cases.
1
Expert's answer
2021-08-25T23:52:46-0400
#include <iostream>
#include <string>
using namespace std;


class DATE{
private:
	int day;
	int month;
	int year;


public:
	// Define default constructor.
	DATE() { this->day = this->month = this->year = 0; }
	DATE(int day,int month,int year) { 
		this->day =day;
		this->month =month;
		this->year = year;
	}


	// Define accessor functions.
	int getDay() { return this->day; }
	int getMonth() { return this->month; }
	int getYear() { return this->year; }


	// Declare prefix and postfix increment operators.
	// Postfix increment operator.
	DATE& operator++(){
		if (day > 0 && day < 28)	//checking for day from 0 to 27
			day += 1;
		if (day == 28)
		{
			if (month == 2)	//checking for february
			{
				if ((year % 400 == 0) || (year % 100 != 0 || year % 4 == 0))	//leap year check in case of feb
				{
					day = 29;
				}
				else
				{
					day = 1;
					month = 3;
				}
			}
			else	//when its not feb
				day += 1;
		}
		if (day == 29)	//last day check for feb
		{
			if (month == 2)
			{
				day = 1;
				month = 3;
			}
			else
				day += 1;
		}
		if (day == 30)	//last day check for april,june,September,November
		{
			if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
				day += 1;
			else
			{
				day = 1;
				month += 1;
			}
		}
		if (day == 31)	//last day of the month
		{
			day = 1;
			if (month == 12)	//checking for last day of the year
			{
				year += 1;
				month = 1;
			}
			else
				month += 1;
		}
		return *this;
	}
	// Prefix increment operator.
	DATE operator++(int){
		DATE temp = *this;
		++*this;
		return temp;
	}   




};






int main()
{
	int day;
	int month;
	int year;




	cout<<"Enter day: ";
	cin>>day;
	cout<<"Enter month: ";
	cin>>month;
	cout<<"Enter year: ";
	cin>>year;


	DATE date(day,month,year);
	cout<<"\nCurrent date:\n";
	cout<<date.getDay()<<"/"<<date.getMonth()<<"/"<<date.getYear()<<"\n";


	
	cout<<"\nPostfix increment operator:\n";
	date++;
	cout<<date.getDay()<<"/"<<date.getMonth()<<"/"<<date.getYear()<<"\n";


	cout<<"\nPrefix increment operator:\n";
	++date;
	cout<<date.getDay()<<"/"<<date.getMonth()<<"/"<<date.getYear()<<"\n";


	cin>>day;
	return 0;

}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS