A class declaration looks similar to a structure declaration, except that it has both functions and data as members, instead of just data. The following is a preliminary version of a class that describes a date.
// The Date class
#include <iostream.h>
// ------------ a Date class
class Date
{
public:
Date( int mn, int dy, int yr ); // Constructor
void display(); // Function to print date
~Date(); // Destructor
private:
int month, day, year; // Private data members
};
This class declaration is roughly equivalent to the combination of an ordinary structure declaration plus a set of function prototypes. It declares the following:
The contents of each instance of Date: the integers month, day, and year. These are the class's “data members.”
The prototypes of three functions that you can use with Date: Date, ~Date, and display. These are the class's “member functions.”
You supply the definitions of the member functions after the class declaration. Here are the definitions of Date's member functions:
// some useful functions
inline int max( int a, int b )
{
if( a > b ) return a;
return b;
}
inline int min( int a, int b )
{
if( a < b ) return a;
return b;
}
// ---------- The constructor
Date::Date( int mn, int dy, int yr )
{
static int length[] = { 0, 31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 };
// Ignore leap years for simplicity
month = max( 1, mn );
month = min( month, 12 );
day = max( 1, dy );
day = min( day, length[month] );
year = max( 1, year );
}
// -------- Member function to printdate
void Date::display()
{
static char *name[] =
{
"zero", "January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November","December"
};
cout << name[month] << ' ' << day << ", " << year;
}
// ---------- The destructor
Date::~Date()
{
// do nothing
}
The display function looks familiar, but the Date and ~Date functions are new. They are called the “constructor” and “destructor,” respectively, and they are used to create and destroy objects, or instances of a class. They are described later in this chapter.
These are not all the member functions that a Date class needs, but they are sufficient to demonstrate the basic syntax for writing a class. Later in this chapter, we'll add more functionality to the class.
Here's a program that uses the rudimentary Date class:
// ========== Program that demonstrates the Date class
void main()
{
Date myDate( 3, 12, 1985 ); // Declare a Date
Date yourDate( 23, 259, 1966 ); // Declare an invalid Date
myDate.display();
cout << '\n';
yourDate.display();
cout << '\n';
}