< previous page page_999 next page >

Page 999
For example, our Date class declaration in Figure 17-10 shows the prototype of the copy-constructor to be
Date( const Date& otherDate );
If a copy-constructor is present, the default method of initialization (member-by-member copying) is inhibited. Instead, the copy-constructor is implicitly invoked whenever one class object is initialized by another. The following implementation of the Date class copy-constructor shows the steps that are involved:
Date::Date( const Date& otherDate )

// Copy-constructor

// Postcondition:
//     mo == otherDate.mo
//  && day == otherDate.day
//  && yr == otherDate.yr
//  && msg points to a duplicate of otherDate' s message string
//     on the free store

{
    mo = otherDate.mo;
    day = otherDate.day;
    yr = otherDate.yr;
    msg = new char[strlen(otherDate.msg) + 1];
    strcpy(msg, otherDate.msg);
}
The body of the copy-constructor function differs from the body of the CopyFrom function in only one line of code: the CopyFrom function executes
delete [] msg;
before allocating a new array. The difference between these two functions is that CopyFrom is copying to an existing class object (which is already pointing to a dynamic array that must be deallocated), whereas the copyconstructor is creating a new class object that doesn't already exist.
Notice the use of the reserved word const in the parameter list of the copy-constructor. The word const ensures that the function cannot alter otherDate, even though otherDate is passed by reference.

 
< previous page page_999 next page >