< previous page page_996 next page >

Page 996
Shallow Versus Deep Copying
Next, let's look at the CopyFrom function of the Date class (Figure 17-10). This function is designed to copy one class object to another, including the dynamic message array. With the built-in assignment operator(=), assignment of one class object to another copies only the class members; it does not copy any data pointed to by the class members. For example, given the date1 and date2 objects of Figure 17-9, the effect of the assignment statement
date1 = date2;
is shown in Figure 17-11. The result is called a shallow copy operation. The pointer is copied, but the pointed-to data are not.
Shallow copying is perfectly fine if none of the class members are pointers. But if one or more members are pointers, then shallow copying may be erroneous. In Figure 17-11, the dynamic array originally pointed to by the datel object has been left inaccessible.
What we want is a deep copy operationone that duplicates not only the class members but also the pointed-to data. The CopyFrom function of the Date class performs a deep copy. Here is the function implementation:
void Date::CopyFrom( /* in */ Date otherDate )

// Postcondition:
//     mo == otherDate.mo
//  && day == otherDate.day
//  && yr == otherDate.yr
//  && msg points to a duplicate of otherDate's message string
//     on the free store
0996-01.gif
Figure 17-11
A Shallow Copy Caused by the Assignment 
date1 = date2

 
< previous page page_996 next page >