patterncppModerate
Is this Date class well-written?
Viewed 0 times
thiswrittendatewellclass
Problem
I'm a C++ beginner and have made a simple class. But I'm not sure if this is well-written. It's basically just a
For example, the arguments of
Date class.#include
using namespace std;
class Date{
int d, m, y; //Day, Month, Year
public:
Date(int dd = 1, int mm = 1, int yy = 1);
int addDay(const int &dd) { d += dd; }
int addMonth(const int &mm) { m += mm; }
int addYear(const int &yy) { y += yy; }
int day() const { return d; }
int month() const { return m; }
int year() const { return y; }
void display() const; //Print to screen
};
void Date::display() const {
cout << d << "." << m << "." << y << endl;
}
Date::Date(int dd, int mm, int yy){
d = dd;
m = mm;
y = yy;
}For example, the arguments of
addDay(const int &dd);. Is that good, or should it just be an integer without const and without reference?Solution
For built-in types, there is no point in passing it as a
Other comments:
You need to make some judgments to design a Date` class properly. I won't give you any further suggestions, because it is a good exercise to think about it. Revise your code, and think about the pros and cons of various approaches. Apart from that and the points above, your code looks OK.
const& - prefer a plain int (or a const int) instead.Other comments:
- Your
add-functions are said to returninteven though you don't have areturnstatement. I don't think that would or should even compile. Change them tovoid.
- Take the time to write out
day,monthandyear. The extra seconds in typing is nothing compared to the readability gain.
- Are you sure you want a default date?
- Consider overloading
operator
- Consider changing your display()
function into ato_stringfunction instead, and have it return astd::string.
- Make your class easy to use correctly, and hard to use incorrectly. What if month
is 12 and someone callsaddMonth()? What is someone passes in June asmonth, but31as day? Isdayday the day of the month, or day of the year? Adhere to the principle of least astonishment. Your class should behave the way users of the class expect it to.
- Don't pollute the global namespace with using namespace std
.
- Split the code into a header and an implementation file. Even though you won't need it now, it's good practice. That makes point 7 even more crucial.
You need to make some judgments to design a Date` class properly. I won't give you any further suggestions, because it is a good exercise to think about it. Revise your code, and think about the pros and cons of various approaches. Apart from that and the points above, your code looks OK.
Context
StackExchange Code Review Q#28339, answer score: 10
Revisions (0)
No revisions yet.