Validation in classes

I have the following class but can't seem to figure out how to validate the inputs.
//Define Default Constructor
DateC::DateC()
{
day = 1;
month = 1;
year = 2000;
}
//Define Constructor
DateC::DateC(int d, int m, int y)
{
day = d;
month = m;
year = y;
}
//Define GetDay
int DateC:: getday()
{
return day;
}
//Define GetMonth
int DateC:: getmonth()
{
return month;
}
//Define GetYear
int DateC:: getyear()
{
return year;
}
I fleshed out your code and showed you one way to validate the month field. You can reuse the validateMonth function if you add a setMonth() function to your class. What you do with the field when validation fails is totally up to you.

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>

class DateC
{
public:
    DateC();
    DateC(int d, int m, int y);
    int getday();
    int getmonth();
    int getyear();
private:
    int day;
    int month;
    int year;

    bool validateMonth(int monthToValidate);
};

//Define Default Constructor
DateC::DateC()
{
    day = 1;
    month = 1;
    year = 2000;
};

//Define Constructor
DateC::DateC(int d, int m, int y)
{
    day = d;

    if (validateMonth(m))
    {
        month = m;
    }
    else
    {
        month = 1;
    }
    year = y;
}

//Define GetDay
int DateC:: getday()
{
    return day;
}
//Define GetMonth
int DateC:: getmonth()
{
    return month;
}
//Define GetYear
int DateC:: getyear()
{
    return year;
}

bool DateC::validateMonth(int monthToValidate)
{
    return ((monthToValidate > 0) && (monthToValidate <= 12));
}

int main()
{
    DateC d1;
    std::cout << d1.getday() << "/" << d1.getmonth() << "/" << d1.getyear() << std::endl;

    DateC d2(11, 3, 2020);
    std::cout << d2.getday() << "/" << d2.getmonth() << "/" << d2.getyear() << std::endl;

    DateC d3(11, 15, 2020); // Illegal month value
    std::cout << d3.getday() << "/" << d3.getmonth() << "/" << d3.getyear() << std::endl;

    return 0;
}
this is the kind of thing you are going to do a lot of, and you may want some sort of tool you can use to validate common things (ints and doubles within ranges for examples). I keep mine as stand alone function / procedural design but you can bundle into an object if you feel a need. Putting them into the class, though, limits re-use, so consider moving it out.
doug4's validateMonth() is a good start, but you'll need more. I suggest a general validate() method that validates the entire date. After all, some days are only valid on some months, or some months in some years (think February 29).
Topic archived. No new replies allowed.