< previous page page_927 next page >

Page 927
The Slicing Problem
Our Print function uses pass-by-value for the formal parameter someTime. Pass-by-value sends a copy of the actual parameter to the formal parameter. Whenever you pass an object of a child class to an object of its parent class using pass-by-value, only the data members they have in common are copied. Remember that a child class is often larger than its parentthat is, it contains additional data members. For example, a Time object has three data members(hrs, mins, and secs), but an ExtTime object has four data members (hrs,mins,secs, and zone). When the larger class object is copied to the smaller formal parameter using pass-by-value, the extra data members are discarded or sliced off. This situation is called the slicing problem (see Figure 16-8).
(The slicing problem also occurs with assignment operations. In the statement
parentClassObject = childClassObject;
only the data members that the two objects have in common are copied. Additional data members contained in childClassObject are not copied.)
With pass-by-reference, the slicing problem does not occur because the address of the actual parameter is sent to the function. Let's change the heading of our Print function so that someTime is a reference parameter:
void Print( /* in */ Time& someTime )
Now when we pass endTime as the actual parameter, its address is sent to the function. Its time zone member is not sliced off because no copying takes place. But to our dismay, the Print function still prints only three of endTime's data membershours, minutes, and seconds. Within the Print function, the difficulty is that static binding is used in the statement
someTime.Write();
The compiler must generate machine language code for the Print function at compile time, but the type of the actual parameter (Time or ExtTime) isn't known until run time. How can the compiler know which Write function to useTime::Write or ExtTime::Write? The compiler cannot know, so it uses Time::Write because the formal parameter someTime is of type Time. Therefore, the Print function always prints just three valueshours, minutes, and secondsregardless of the type of the actual parameter. Fortunately, C++ provides a very simple solution to our problem: virtual functions.

 
< previous page page_927 next page >