< previous page page_1000 next page >

Page 1000
As with any nonarray variable in C++, a class object can be passed to a function either by value or by reference. Because C++ defines initialization to include pass-by-value, copy-constructors are vitally important when class objects point to dynamic data. Assume that we did not include a copy-constructor for the Date class, and assume that the following call to the DoSomething function uses pass-by-value:
int main()
{
    Date quizDate(2, 18, 1998, Geography quiz);
      .
      .
      .
    DoSomething(quizDate);
      .
      .
      .
Without a copy-constructor, quizDate would be copied to the DoSomething function's formal parameter using a shallow copy. A copy of quizDate's dynamic array would not be created for use within DoSomething. Both quizDate and the formal parameter within DoSomething would point to the same dynamic array (see Figure 17-13). If the DoSomething function were to modify the dynamic array (thinking it is working on a copy of the original), then after the function returns, quizDate would point to a corrupted dynamic array.
1000-01.gif
Figure 17-13
Shallow Copy Caused by Pass-by-Value without a Copy-Constructor

 
< previous page page_1000 next page >