< previous page page_863 next page >

Page 863
Guaranteed Initialization with Class Constructors
The TimeType class we have been discussing has a weakness. It depends on the client to invoke the Set function before calling any other member function. For example, the Increment function's precondition is
// Precondition:
//     The Set function has been invoked at least once
If the client fails to invoke the Set function first, this precondition is false and the contract between the client and the function implementation is broken. Because classes nearly always encapsulate data, the creator of a class should not rely on the user to initialize the data. If the user forgets to, unpleasant results may occur.
C++ provides a mechanism, called a class constructor, to guarantee the initialization of a class object. A constructor is a member function that is implicitly invoked whenever a class object is created.
A constructor function has an unusual name: the name of the class itself. Let's change the TimeType class by adding two class constructors:
class TimeType
{
public:
    void    Set( int, int, int );
    void    Increment();
    void    Write() const;
    Boolean Equal( TimeType ) const;
    Boolean LessThan( TimeType ) const;
    TimeType( int, int, int );           // Constructor
    TimeType();                          // Constructor
private:
    int hrs;
    int mins;
    int secs;
};
This class declaration includes two constructors, differentiated by their parameter lists. The first has three int parameters which, as we will see, are used to initialize the private data when a class object is created. The second constructor is parameterless and initializes the time to some default value, such as 0:0:0. A parameterless constructor is known in C++ as a default constructor.
Constructor declarations are unique in two ways. First, as we have mentioned, the name of the function is the same as the name of the class. Sec-

 
< previous page page_863 next page >