Is there an error in this code?

Mar 15, 2017 at 4:28am
Hello all! I am studying for my midterm and I went through my profs powerpoint and she asked if there is anything wrong with this code:

Any problem with this
code segment?
A) Yes
B) No

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Date {
private:
int m_year, m_month, m_day;
public:
Date(int year, int month, int day)
{ setDate(year, month, day); }
void setDate(int year, int month, int day)
{ m_year = year;
m_month = month;
m_day = day;
}
int getYear() { return m_year; }
int getMonth() { return m_month; }
int getDay() { return m_day; }
};

// Pass date by const reference to avoid making a copy of date
void printDate(const Date &date)
{ cout<<date.getYear()<<"/"<<date.getMonth()<<"/"<<date.getDay(); }
int main()
{ Date date(2016, 10, 16);
printDate(date);
return 0;
}


I cant really find anything except the constructor looks funky. But can someone catch something and why is it wrong? thank you my friends!
Mar 15, 2017 at 9:50am
Try to compile it and then see if there are any problems.
Mar 16, 2017 at 6:14pm
getYear(), getMonth() and getDate() must be declared const if you want to use them with a const object.
That's what you try to do here:
cout<<date.getYear()<<"/"<<date.getMonth()<<"/"<<date.getDay();
date is declared const (const Date &date)
Topic archived. No new replies allowed.