I'm trying to teach myself classes. I decided to create a class to represent a date. It's more for me to learn than to actually be useful. When I have the variables month, day, and year under private setting, the program will not compile (I am using Dev C++). When I move these three variables under public, the program compiles and works exactly as I want it to. I believe I have accessors and mutators set up properly, but if not please let me know. Why do these not work under a private setting?
Here is the date.h (with variables under private setting) file, and the date.cpp file. If you need to see the driver file let me know.
//date.h
using namespace std;
class date
{
private:
int month, day, year; /*Variables under private setting, where
they don't work.*/
public:
/* When I move the variables (int month, day, year) here under the
public setting the program works. Why is this so? */
//Default constructor.
date();
//Parametized constructor.
date(int newmonth, int newday, int newyear);
//Accessor methods.
double getmonth() const;
double getday() const;
double getyear() const;
//Mutator methods.
void changemonth(int newmonth);
void changeday(int newday);
void changeyear(int newyear);
//Additional functions.
//Print date in the form (#month/#day/#year).
void numform(date d1);
//Print date in the form (Month #day, year).
void wordform(date d1);
};
/**************************************************************************************/
//date.cpp
#include "date.h"
#include<string>
#include<iostream>
using namespace std;
//Default constructor.
date::date()
{
month=1;
day=1;
year=2000;
}
//Parametized constructor.
date::date(int newmonth, int newday, int newyear)
{
month=newmonth;
day=newday;
year=newyear;
}
//Accessor methods.
double date::getmonth() const
{
return month;
}
double date::getday() const
{
return day;
}
double date::getyear() const
{
return year;
}
//Mutator methods.
void date::changemonth(int newmonth)
{
month=newmonth;
}
void date::changeday(int newday)
{
day=newday;
}
void date::changeyear(int newyear)
{
year=newyear;
}
//Additional functions.
//Numerical form.
void date::numform(date d1)
{
cout<<month<<"/"<<day<<"/"<<year<<"\n";
}
//Written form.
void date::wordform(date d1)
{
string monthword;
switch(d1.month)
{
case 1:
monthword="January";
break;
case 2:
monthword="February";
break;
case 3:
monthword="March";
break;
case 4:
monthword="April";
break;
case 5:
monthword="May";
break;
case 6:
monthword="June";
break;
case 7:
monthword="July";
break;
case 8:
monthword="August";
break;
case 9:
monthword="September";
break;
case 10:
monthword="October";
break;
case 11:
monthword="November";
break;
case 12:
monthword="December";
break;
}
cout<<monthword<<" "<<d1.day<<", "<<d1.year<<"\n";
}