The Constructor

Remember that the date structure in C had the drawback of not guaranteeing that it contained valid values. In C++, one way to ensure that objects always contain valid values is to write a constructor. A constructor is a special initialization function that is called automatically whenever an instance of your class is declared. This function prevents errors resulting from the use of uninitialized objects.

The constructor must have the same name as the class itself. For example, the constructor for the Date class is named Date.

Look at the implementation of the Date 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 );

}

Not only does this function initialize the object's data members, it also checks that the specified values are valid; if a value is out of range, it substitutes the closest legal value. This is another way that a constructor can ensure that objects contains meaningful values.

Whenever an instance of a class comes into scope, the constructor is executed. Observe the declaration of myDate in the main function:

Date myDate( 3, 12, 1985 );

The syntax for declaring an object is similar to that for declaring an integer variable. You give the data type (in this case, Date) and then the name of the object, myDate.

However, this object's declaration also contains an argument list in parentheses. These arguments are passed to the constructor function and are used to initialize the object. When you declare an integer variable, the program merely allocates enough memory to store the integer; it doesn't initialize that memory. When you declare an object, your constructor function initializes its data members.

You cannot specify a return type when declaring a constructor, not even void. Consequently, a constructor cannot contain a return statement. A constructor doesn't return a value, it creates an object.

You can declare more than one constructor for a class if they have different parameter lists; that is, you can overload the constructor. This is useful if you want to initialize your objects in more than one way. This is demonstrated in the section “Accessing Data Members”.

You aren't required to define any constructors when you define a class, but it is a good idea to do so. If you don't define any, the compiler automatically generates a do-nothing constructor that takes no parameters, just so you can declare instances of the class. However, this compiler-generated constructor doesn't initialize any data members, so any objects you declare are not any safer than C structures.