SlideShare a Scribd company logo
1 of 6
Download to read offline
Modify the Date class that was covered in the lecture which overloaded the increment and stream
insertion operators.
The new version of the class should have the following overloaded operators:
(=) subtraction assignment operator :: subtracts the right operand from the left operand and
assigns the result to the left operand.
This operator should cause appropriate number of decrements to the object's 'day' member. It
also checks appropriate decrements to the 'month' and 'year' data members, if necessary.
(>>) cin 's stream extraction operator :: This operator should prompt the user for a date to be
stored in a Date object (you can specify your own format and prompt the user for the same).
Write a driver program and test the operators with the Date objects.
The program should have the following additional requirements:
The operator overloaded functions should be non-member functions.
Input validation (day, month) for the Date object.
The subtraction assignment operator (=) should work with end of month, end of year, and leap
year conditions as shown in the example output below.
Minimum three files (main.cpp, Date.h, Date.cpp). Submit your code as:
LastName_FirstName_Q2.zip (containing all files).
Example output:
Enter a date in format mm-dd-yyyy
01-01-2023
Date d1 is: January 1, 2023 // Check a valid date
Date (d1 -= 3) is: December 29, 2022 // Decrement by 3 days
Date d2 is: March 2, 2008
Date (d2-=2) is: February 29, 2008 // leap year has 29 days
Date.h
// Fig. 10.6: Date.h
// Date class definition with overloaded increment operators.
#ifndef DATE_H
#define DATE_H
#include
#include
class Date {
friend std::ostream& operator<<(std::ostream&, const Date&);
public:
Date(int m = 1, int d = 1, int y = 1900); // default constructor
void setDate(int, int, int); // set month, day, year
Date& operator++(); // prefix increment operator
Date operator++(int); // postfix increment operator
Date& operator+=(unsigned int); // add days, modify object
static bool leapYear(int); // is year a leap year?
bool endOfMonth(int) const; // is day at the end of month?
private:
unsigned int month;
unsigned int day;
unsigned int year;
static const std::array days; // days per month
void helpIncrement(); // utility function for incrementing date
};
#endif
Date.cpp
#include
#include
#include "Date.h"
using namespace std;
// initialize static member; one classwide copy
const array Date::days{
0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Date constructor
Date::Date(int month, int day, int year) {
setDate(month, day, year);
}
// set month, day and year
void Date::setDate(int mm, int dd, int yy) {
if (mm >= 1 && mm <= 12) {
month = mm;
}
else {
throw invalid_argument{"Month must be 1-12"};
}
if (yy >= 1900 && yy <= 2100) {
year = yy;
}
else {
throw invalid_argument{"Year must be >= 1900 and <= 2100"};
}
// test for a leap year
if ((month == 2 && leapYear(year) && dd >= 1 && dd <= 29) ||
(dd >= 1 && dd <= days[month])) {
day = dd;
}
else {
throw invalid_argument{
"Day is out of range for current month and year"};
}
}
// overloaded prefix increment operator
Date& Date::operator++() {
helpIncrement(); // increment date
return *this; // reference return to create an lvalue
}
// overloaded postfix increment operator; note that the
// dummy integer parameter does not have a parameter name
Date Date::operator++(int) {
Date temp{*this}; // hold current state of object
helpIncrement();
// return unincremented, saved, temporary object
return temp; // value return; not a reference return
}
// add specified number of days to date
Date& Date::operator+=(unsigned int additionalDays) {
for (unsigned int i = 0; i < additionalDays; ++i) {
helpIncrement();
}
return *this; // enables cascading
}
// if the year is a leap year, return true; otherwise, return false
bool Date::leapYear(int testYear) {
return (testYear % 400 == 0 ||
(testYear % 100 != 0 && testYear % 4 == 0));
}
// determine whether the day is the last day of the month
bool Date::endOfMonth(int testDay) const {
if (month == 2 && leapYear(year)) {
return testDay == 29; // last day of Feb. in leap year
}
else {
return testDay == days[month];
}
}
// function to help increment the date
void Date::helpIncrement() {
// day is not end of month
if (!endOfMonth(day)) {
++day; // increment day
}
else {
if (month < 12) { // day is end of month and month < 12
++month; // increment month
day = 1; // first day of new month
}
else { // last day of year
++year; // increment year
month = 1; // first month of new year
day = 1; // first day of new month
}
}
}
// overloaded output operator
ostream& operator<<(ostream& output, const Date& d) {
static string monthName[13]{"", "January", "February",
"March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"};
output << monthName[d.month] << ' ' << d.day << ", " << d.year;
return output; // enables cascading
}
main.cpp
#include
#include "Date.h" // Date class definition
using namespace std;
int main() {
Date d1{12, 27, 2010}; // December 27, 2010
Date d2; // defaults to January 1, 1900
cout << "d1 is " << d1 << "nd2 is " << d2;
cout << "nnd1 += 7 is " << (d1 += 7);
d2.setDate(2, 28, 2008);
cout << "nn d2 is " << d2;
cout << "n++d2 is " << ++d2 << " (leap year allows 29th)";
Date d3{7, 13, 2010};
cout << "nnTesting the prefix increment operator:n"
<< " d3 is " << d3 << endl;
cout << "++d3 is " << ++d3 << endl;
cout << " d3 is " << d3;
cout << "nnTesting the postfix increment operator:n"
<< " d3 is " << d3 << endl;
cout << "d3++ is " << d3++ << endl;
cout << " d3 is " << d3 << endl;
}

More Related Content

Similar to Modify the Date class that was covered in the lecture which overload.pdf

CMPSC 122 Project 1 Back End Report
CMPSC 122 Project 1 Back End ReportCMPSC 122 Project 1 Back End Report
CMPSC 122 Project 1 Back End Report
Matthew Zackschewski
 
publicclass Date {privatestatic String DATE_SEPARATOR = ;pr.pdf
publicclass Date {privatestatic String DATE_SEPARATOR = ;pr.pdfpublicclass Date {privatestatic String DATE_SEPARATOR = ;pr.pdf
publicclass Date {privatestatic String DATE_SEPARATOR = ;pr.pdf
mukhtaransarcloth
 
Problem DefinitionBuild a Date class and a main function to test i.pdf
Problem DefinitionBuild a Date class and a main function to test i.pdfProblem DefinitionBuild a Date class and a main function to test i.pdf
Problem DefinitionBuild a Date class and a main function to test i.pdf
smitaguptabootique
 
CounterTest.javaimport static org.junit.Assert.;import org.jun.pdf
CounterTest.javaimport static org.junit.Assert.;import org.jun.pdfCounterTest.javaimport static org.junit.Assert.;import org.jun.pdf
CounterTest.javaimport static org.junit.Assert.;import org.jun.pdf
deepua8
 
Date.h#ifndef DateFormat#define DateFormat#includetime.h.pdf
Date.h#ifndef DateFormat#define DateFormat#includetime.h.pdfDate.h#ifndef DateFormat#define DateFormat#includetime.h.pdf
Date.h#ifndef DateFormat#define DateFormat#includetime.h.pdf
angelfragranc
 
#include iostream #includeData.h #includePerson.h#in.pdf
#include iostream #includeData.h #includePerson.h#in.pdf#include iostream #includeData.h #includePerson.h#in.pdf
#include iostream #includeData.h #includePerson.h#in.pdf
annucommunication1
 
In this assignment, you will continue working on your application..docx
In this assignment, you will continue working on your application..docxIn this assignment, you will continue working on your application..docx
In this assignment, you will continue working on your application..docx
jaggernaoma
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
exxonzone
 
in C++ Design a class named Employee The class should keep .pdf
in C++ Design a class named Employee The class should keep .pdfin C++ Design a class named Employee The class should keep .pdf
in C++ Design a class named Employee The class should keep .pdf
adithyaups
 

Similar to Modify the Date class that was covered in the lecture which overload.pdf (20)

CMPSC 122 Project 1 Back End Report
CMPSC 122 Project 1 Back End ReportCMPSC 122 Project 1 Back End Report
CMPSC 122 Project 1 Back End Report
 
C++lecture9
C++lecture9C++lecture9
C++lecture9
 
publicclass Date {privatestatic String DATE_SEPARATOR = ;pr.pdf
publicclass Date {privatestatic String DATE_SEPARATOR = ;pr.pdfpublicclass Date {privatestatic String DATE_SEPARATOR = ;pr.pdf
publicclass Date {privatestatic String DATE_SEPARATOR = ;pr.pdf
 
Problem DefinitionBuild a Date class and a main function to test i.pdf
Problem DefinitionBuild a Date class and a main function to test i.pdfProblem DefinitionBuild a Date class and a main function to test i.pdf
Problem DefinitionBuild a Date class and a main function to test i.pdf
 
Computer programming 2 Lesson 14
Computer programming 2  Lesson 14Computer programming 2  Lesson 14
Computer programming 2 Lesson 14
 
OOPS 22-23 (1).pptx
OOPS 22-23 (1).pptxOOPS 22-23 (1).pptx
OOPS 22-23 (1).pptx
 
CounterTest.javaimport static org.junit.Assert.;import org.jun.pdf
CounterTest.javaimport static org.junit.Assert.;import org.jun.pdfCounterTest.javaimport static org.junit.Assert.;import org.jun.pdf
CounterTest.javaimport static org.junit.Assert.;import org.jun.pdf
 
Date.h#ifndef DateFormat#define DateFormat#includetime.h.pdf
Date.h#ifndef DateFormat#define DateFormat#includetime.h.pdfDate.h#ifndef DateFormat#define DateFormat#includetime.h.pdf
Date.h#ifndef DateFormat#define DateFormat#includetime.h.pdf
 
(2) cpp abstractions abstraction_and_encapsulation
(2) cpp abstractions abstraction_and_encapsulation(2) cpp abstractions abstraction_and_encapsulation
(2) cpp abstractions abstraction_and_encapsulation
 
Functional C++
Functional C++Functional C++
Functional C++
 
#include iostream #includeData.h #includePerson.h#in.pdf
#include iostream #includeData.h #includePerson.h#in.pdf#include iostream #includeData.h #includePerson.h#in.pdf
#include iostream #includeData.h #includePerson.h#in.pdf
 
201801 CSE240 Lecture 15
201801 CSE240 Lecture 15201801 CSE240 Lecture 15
201801 CSE240 Lecture 15
 
In this assignment, you will continue working on your application..docx
In this assignment, you will continue working on your application..docxIn this assignment, you will continue working on your application..docx
In this assignment, you will continue working on your application..docx
 
Lecture5
Lecture5Lecture5
Lecture5
 
COW
COWCOW
COW
 
C# Assignmet Help
C# Assignmet HelpC# Assignmet Help
C# Assignmet Help
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
 
Overloading
OverloadingOverloading
Overloading
 
datetimefuction-170413055211.pptx
datetimefuction-170413055211.pptxdatetimefuction-170413055211.pptx
datetimefuction-170413055211.pptx
 
in C++ Design a class named Employee The class should keep .pdf
in C++ Design a class named Employee The class should keep .pdfin C++ Design a class named Employee The class should keep .pdf
in C++ Design a class named Employee The class should keep .pdf
 

More from saxenaavnish1

Mini Case identificaci�n de los clientes adecuados para el ka de Fo.pdf
Mini Case identificaci�n de los clientes adecuados para el ka de Fo.pdfMini Case identificaci�n de los clientes adecuados para el ka de Fo.pdf
Mini Case identificaci�n de los clientes adecuados para el ka de Fo.pdf
saxenaavnish1
 
me quedan 35 munites por favor ayudenme Art�culo 1 En el caso .pdf
me quedan 35 munites por favor ayudenme Art�culo 1 En el caso .pdfme quedan 35 munites por favor ayudenme Art�culo 1 En el caso .pdf
me quedan 35 munites por favor ayudenme Art�culo 1 En el caso .pdf
saxenaavnish1
 
MCQ Select the correct answer.1. What does SQL stand fora.pdf
MCQ  Select the correct answer.1. What does SQL stand fora.pdfMCQ  Select the correct answer.1. What does SQL stand fora.pdf
MCQ Select the correct answer.1. What does SQL stand fora.pdf
saxenaavnish1
 
media luna pura Sarah Ryan, vicepresidenta de marketing de Portlan.pdf
media luna pura Sarah Ryan, vicepresidenta de marketing de Portlan.pdfmedia luna pura Sarah Ryan, vicepresidenta de marketing de Portlan.pdf
media luna pura Sarah Ryan, vicepresidenta de marketing de Portlan.pdf
saxenaavnish1
 
my code doesnt work can you help me please the whole idea of is it i.pdf
my code doesnt work can you help me please the whole idea of is it i.pdfmy code doesnt work can you help me please the whole idea of is it i.pdf
my code doesnt work can you help me please the whole idea of is it i.pdf
saxenaavnish1
 
MTCR es una empresa l�der en el desarrollo y fabricaci�n de una ampl.pdf
MTCR es una empresa l�der en el desarrollo y fabricaci�n de una ampl.pdfMTCR es una empresa l�der en el desarrollo y fabricaci�n de una ampl.pdf
MTCR es una empresa l�der en el desarrollo y fabricaci�n de una ampl.pdf
saxenaavnish1
 

More from saxenaavnish1 (20)

Mire el documental Am�rica se convierte en una potencia mundial, lea.pdf
Mire el documental Am�rica se convierte en una potencia mundial, lea.pdfMire el documental Am�rica se convierte en una potencia mundial, lea.pdf
Mire el documental Am�rica se convierte en una potencia mundial, lea.pdf
 
Mini Case identificaci�n de los clientes adecuados para el ka de Fo.pdf
Mini Case identificaci�n de los clientes adecuados para el ka de Fo.pdfMini Case identificaci�n de los clientes adecuados para el ka de Fo.pdf
Mini Case identificaci�n de los clientes adecuados para el ka de Fo.pdf
 
Millie Larsen es una mujer de 84 a�os que vive sola en una casa pequ.pdf
Millie Larsen es una mujer de 84 a�os que vive sola en una casa pequ.pdfMillie Larsen es una mujer de 84 a�os que vive sola en una casa pequ.pdf
Millie Larsen es una mujer de 84 a�os que vive sola en una casa pequ.pdf
 
Miles, a 20 year old male, is seeking counseling because his paterna.pdf
Miles, a 20 year old male, is seeking counseling because his paterna.pdfMiles, a 20 year old male, is seeking counseling because his paterna.pdf
Miles, a 20 year old male, is seeking counseling because his paterna.pdf
 
Mike s 3, p 2Leo s 2 , p 2Don s 1 , p 2April s 3 , p 1.pdf
Mike  s 3, p 2Leo  s 2 , p 2Don s 1 , p 2April  s 3 , p 1.pdfMike  s 3, p 2Leo  s 2 , p 2Don s 1 , p 2April  s 3 , p 1.pdf
Mike s 3, p 2Leo s 2 , p 2Don s 1 , p 2April s 3 , p 1.pdf
 
Miguel is the managing general partner of MAR and owns a 40 interes.pdf
Miguel is the managing general partner of MAR and owns a 40 interes.pdfMiguel is the managing general partner of MAR and owns a 40 interes.pdf
Miguel is the managing general partner of MAR and owns a 40 interes.pdf
 
Michael Porter de Harvard ha propuesto la cadena de valor como una h.pdf
Michael Porter de Harvard ha propuesto la cadena de valor como una h.pdfMichael Porter de Harvard ha propuesto la cadena de valor como una h.pdf
Michael Porter de Harvard ha propuesto la cadena de valor como una h.pdf
 
Microbiology Describe the relationship between DNA and RNA con.pdf
Microbiology Describe the relationship between DNA and RNA con.pdfMicrobiology Describe the relationship between DNA and RNA con.pdf
Microbiology Describe the relationship between DNA and RNA con.pdf
 
Michael leases a Lucerne farm to Boaz for a term of three years. Aft.pdf
Michael leases a Lucerne farm to Boaz for a term of three years. Aft.pdfMichael leases a Lucerne farm to Boaz for a term of three years. Aft.pdf
Michael leases a Lucerne farm to Boaz for a term of three years. Aft.pdf
 
me quedan 35 munites por favor ayudenme Art�culo 1 En el caso .pdf
me quedan 35 munites por favor ayudenme Art�culo 1 En el caso .pdfme quedan 35 munites por favor ayudenme Art�culo 1 En el caso .pdf
me quedan 35 munites por favor ayudenme Art�culo 1 En el caso .pdf
 
Mendel logr� descubrir las leyes b�sicas de la herencia, mientras qu.pdf
Mendel logr� descubrir las leyes b�sicas de la herencia, mientras qu.pdfMendel logr� descubrir las leyes b�sicas de la herencia, mientras qu.pdf
Mendel logr� descubrir las leyes b�sicas de la herencia, mientras qu.pdf
 
MCQ Select the correct answer.1. What does SQL stand fora.pdf
MCQ  Select the correct answer.1. What does SQL stand fora.pdfMCQ  Select the correct answer.1. What does SQL stand fora.pdf
MCQ Select the correct answer.1. What does SQL stand fora.pdf
 
MCQ Pls Help ACC495 Corporate Governance and Risk Management Which .pdf
MCQ Pls Help ACC495 Corporate Governance and Risk Management Which .pdfMCQ Pls Help ACC495 Corporate Governance and Risk Management Which .pdf
MCQ Pls Help ACC495 Corporate Governance and Risk Management Which .pdf
 
Megan se gradu� de la universidad hace tres a�os y ha estado trabaja.pdf
Megan se gradu� de la universidad hace tres a�os y ha estado trabaja.pdfMegan se gradu� de la universidad hace tres a�os y ha estado trabaja.pdf
Megan se gradu� de la universidad hace tres a�os y ha estado trabaja.pdf
 
media luna pura Sarah Ryan, vicepresidenta de marketing de Portlan.pdf
media luna pura Sarah Ryan, vicepresidenta de marketing de Portlan.pdfmedia luna pura Sarah Ryan, vicepresidenta de marketing de Portlan.pdf
media luna pura Sarah Ryan, vicepresidenta de marketing de Portlan.pdf
 
my code doesnt work can you help me please the whole idea of is it i.pdf
my code doesnt work can you help me please the whole idea of is it i.pdfmy code doesnt work can you help me please the whole idea of is it i.pdf
my code doesnt work can you help me please the whole idea of is it i.pdf
 
Must be in C++ programming The main objective of this experiment i.pdf
Must be in C++ programming The main objective of this experiment i.pdfMust be in C++ programming The main objective of this experiment i.pdf
Must be in C++ programming The main objective of this experiment i.pdf
 
MUS monetary unit samplingA) What is the planned sample sizeB).pdf
MUS monetary unit samplingA) What is the planned sample sizeB).pdfMUS monetary unit samplingA) What is the planned sample sizeB).pdf
MUS monetary unit samplingA) What is the planned sample sizeB).pdf
 
Multifactor authentication (MFA) requires users to authenticate thei.pdf
Multifactor authentication (MFA) requires users to authenticate thei.pdfMultifactor authentication (MFA) requires users to authenticate thei.pdf
Multifactor authentication (MFA) requires users to authenticate thei.pdf
 
MTCR es una empresa l�der en el desarrollo y fabricaci�n de una ampl.pdf
MTCR es una empresa l�der en el desarrollo y fabricaci�n de una ampl.pdfMTCR es una empresa l�der en el desarrollo y fabricaci�n de una ampl.pdf
MTCR es una empresa l�der en el desarrollo y fabricaci�n de una ampl.pdf
 

Recently uploaded

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 

Recently uploaded (20)

Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 

Modify the Date class that was covered in the lecture which overload.pdf

  • 1. Modify the Date class that was covered in the lecture which overloaded the increment and stream insertion operators. The new version of the class should have the following overloaded operators: (=) subtraction assignment operator :: subtracts the right operand from the left operand and assigns the result to the left operand. This operator should cause appropriate number of decrements to the object's 'day' member. It also checks appropriate decrements to the 'month' and 'year' data members, if necessary. (>>) cin 's stream extraction operator :: This operator should prompt the user for a date to be stored in a Date object (you can specify your own format and prompt the user for the same). Write a driver program and test the operators with the Date objects. The program should have the following additional requirements: The operator overloaded functions should be non-member functions. Input validation (day, month) for the Date object. The subtraction assignment operator (=) should work with end of month, end of year, and leap year conditions as shown in the example output below. Minimum three files (main.cpp, Date.h, Date.cpp). Submit your code as: LastName_FirstName_Q2.zip (containing all files). Example output: Enter a date in format mm-dd-yyyy 01-01-2023 Date d1 is: January 1, 2023 // Check a valid date Date (d1 -= 3) is: December 29, 2022 // Decrement by 3 days Date d2 is: March 2, 2008 Date (d2-=2) is: February 29, 2008 // leap year has 29 days Date.h // Fig. 10.6: Date.h // Date class definition with overloaded increment operators. #ifndef DATE_H #define DATE_H #include #include
  • 2. class Date { friend std::ostream& operator<<(std::ostream&, const Date&); public: Date(int m = 1, int d = 1, int y = 1900); // default constructor void setDate(int, int, int); // set month, day, year Date& operator++(); // prefix increment operator Date operator++(int); // postfix increment operator Date& operator+=(unsigned int); // add days, modify object static bool leapYear(int); // is year a leap year? bool endOfMonth(int) const; // is day at the end of month? private: unsigned int month; unsigned int day; unsigned int year; static const std::array days; // days per month void helpIncrement(); // utility function for incrementing date }; #endif Date.cpp #include #include #include "Date.h" using namespace std; // initialize static member; one classwide copy const array Date::days{ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Date constructor Date::Date(int month, int day, int year) {
  • 3. setDate(month, day, year); } // set month, day and year void Date::setDate(int mm, int dd, int yy) { if (mm >= 1 && mm <= 12) { month = mm; } else { throw invalid_argument{"Month must be 1-12"}; } if (yy >= 1900 && yy <= 2100) { year = yy; } else { throw invalid_argument{"Year must be >= 1900 and <= 2100"}; } // test for a leap year if ((month == 2 && leapYear(year) && dd >= 1 && dd <= 29) || (dd >= 1 && dd <= days[month])) { day = dd; } else { throw invalid_argument{ "Day is out of range for current month and year"}; } } // overloaded prefix increment operator Date& Date::operator++() { helpIncrement(); // increment date return *this; // reference return to create an lvalue } // overloaded postfix increment operator; note that the // dummy integer parameter does not have a parameter name Date Date::operator++(int) { Date temp{*this}; // hold current state of object helpIncrement();
  • 4. // return unincremented, saved, temporary object return temp; // value return; not a reference return } // add specified number of days to date Date& Date::operator+=(unsigned int additionalDays) { for (unsigned int i = 0; i < additionalDays; ++i) { helpIncrement(); } return *this; // enables cascading } // if the year is a leap year, return true; otherwise, return false bool Date::leapYear(int testYear) { return (testYear % 400 == 0 || (testYear % 100 != 0 && testYear % 4 == 0)); } // determine whether the day is the last day of the month bool Date::endOfMonth(int testDay) const { if (month == 2 && leapYear(year)) { return testDay == 29; // last day of Feb. in leap year } else { return testDay == days[month]; } } // function to help increment the date void Date::helpIncrement() { // day is not end of month if (!endOfMonth(day)) { ++day; // increment day } else { if (month < 12) { // day is end of month and month < 12 ++month; // increment month day = 1; // first day of new month } else { // last day of year
  • 5. ++year; // increment year month = 1; // first month of new year day = 1; // first day of new month } } } // overloaded output operator ostream& operator<<(ostream& output, const Date& d) { static string monthName[13]{"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; output << monthName[d.month] << ' ' << d.day << ", " << d.year; return output; // enables cascading } main.cpp #include #include "Date.h" // Date class definition using namespace std; int main() { Date d1{12, 27, 2010}; // December 27, 2010 Date d2; // defaults to January 1, 1900 cout << "d1 is " << d1 << "nd2 is " << d2; cout << "nnd1 += 7 is " << (d1 += 7); d2.setDate(2, 28, 2008); cout << "nn d2 is " << d2; cout << "n++d2 is " << ++d2 << " (leap year allows 29th)"; Date d3{7, 13, 2010}; cout << "nnTesting the prefix increment operator:n" << " d3 is " << d3 << endl; cout << "++d3 is " << ++d3 << endl; cout << " d3 is " << d3; cout << "nnTesting the postfix increment operator:n" << " d3 is " << d3 << endl;
  • 6. cout << "d3++ is " << d3++ << endl; cout << " d3 is " << d3 << endl; }