C++ program of class date according to the rule of calendar

//i have an issue with the code i want to run it according to the rules of calendar mean to say if i enter month=2 year =2020 and day=30 it change day 30 to default value because feb have no 30date please solve this.

#include <iostream>
using namespace std;
class date
{
private:
int day;
int month;
int year;

public:
date()
{
setday(1);
setmonth(1);
setyear(2021);
}
void setyear(int y)
{
if (y >= 1930 && y <= 2021)
{
year = y;
}
else
{
year = 2021;
}
}
void setmonth(int m)
{
if (m >= 1 && m <= 12)
{
month = m;
}
else
month = 1;
}
void setday(int d)
{
if (d >= 1 && d <= 31)
{
day = d;
}
else
day = 1;
}

void displayinfo()
{
cout << "Day : " << day << endl;
cout << "Month : " << month << endl;
cout << "Year : " << year << endl;
}
};
int main()
{
date d;
d.setday(2);
d.setmonth(4);
d.setyear(2020);
d.displayinfo();
}
Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
using namespace std;

class date
{
public:
	date() {}

	date(int d, int m, int y) {
		setyear(y);
		setmonth(m);
		setday(d);
	}

	bool isleap()
	{
		return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
	}

	void displayinfo()
	{
		cout << "Day : " << day << '\n';
		cout << "Month : " << month << '\n';
		cout << "Year : " << year << '\n';
	}

private:
	inline static const int days[12] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

	int day {1};
	int month {1};
	int year {2021};

	void setyear(int y) { year = y >= 1930 && y <= 2021 ? y : 2021; }

	void setmonth(int m) { month = m >= 1 && m <= 12 ? m : 1; }

	void setday(int d)
	{
		day = d >= 1 && d <= days[month - 1] + (month == 2 && isleap()) ? d : 1;
	}
};

int main()
{
	date d(2, 4, 2020);

	d.displayinfo();
}

Topic archived. No new replies allowed.