I have this class:
class Date
{
public:
Date(); // Sets a date of January 1, 2000
Date(int mm, int dd, int yyyy); // Sets a date with the passed arguments; automatically converts two-digit years as being AFTER the year 2000
Date after_period_of ( int days ) const; // Elapses an arbitrary amount of time, and returns a new date
string mmddyy () const; // Returns date in MM/DD/YY format (1/1/00)
string full_date () const; // Returns date in full format (January 1, 2000)
string month_name () const; // Returns the name of the month as a string;
private:
int days_in_february(int yr);
int month;
int day;
int year;
};
When I try to pass private variable year as an argument into days_in_february, I get the following error message:
passing ‘const Date’ as ‘this’ argument of ‘int Date::days_in_february(int)’ discards qualifiers
days_in_february is called in after_period_of, like this:
Date Date::after_period_of (int days_elapsed) const
{
int new_month;
int new_year = year; // tried copying 'year' to get around this issue, but it did not help
int days_into_new_month;
int max_days_in_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } ;
max_days_in_month[1] = days_in_february(new_year);
and again in the same function:
if (new_month == 13)
{
new_month = 1;
new_year += 1;
max_days_in_month[1] = days_in_february(new_year);
}
days_in_february simply returns the number 28 or 29 based on year that is passed into it. It does not attempt to manipulate anything outside of its own block.
I have even tried to pass a non-programmed variable into it (days_in_february(2000)) and I get the same error.I’ve tried moving that function into the public domain, but that didn’t fix the issue either.
Why is this happening?
Why am I not allowed to do this?
Inside
after_period_of, you cannot access non-constant functions; in particular, you cannot accessdays_in_february. You can fix this by also declaring the latter functionconst.