1: // Filename: TIMESLIC.CPP 2: // Purpose: Illustrates the "slicing problem", one of the 3: // problems that virtual functions help to solve. 5: #include <iostream> 6: using namespace std; 8: #include "TIME.H" 9: #include "ZONETIME.H" 12: void DisplayTimeWithBanner(/* in */ Time someTime) 13: // Pre: someTime contains a Time object or an object of a derived class. 14: // Post: The value in someTime has been displayed in "banner form". 15: { 16: cout << "***************************\n"; 17: cout << "** The time is "; 18: someTime.Display(); cout << endl; 19: cout << "***************************\n\n"; 20: } 23: int main() 24: { 25: Time myTime(8, 30, 0); 26: ZoneTime yourTime(10, 45, 0, CST); 28: cout << endl; 29: DisplayTimeWithBanner(myTime); 30: // Output is what you would expect, since myTime 31: // is an object from the class Time. 33: DisplayTimeWithBanner(yourTime); 34: // Output is not what you would hope for. Since yourTime is 35: // an object of class ZoneTime, and is thus also a Time (any 36: // ZoneTime "is a" Time, because of inheritance), you would 37: // hope that the value of the ZoneTime would be printed out. 38: // Unfortunately, the ZoneTime value is "bigger than" the 39: // Time value (occupies more storage space in memory because 40: // of the additional member variable) but the "extra part" is 41: // "sliced off" as it is passed to the DisplayTimeWithBanner 42: // function because it is passed by value and a copy is made to 43: // a local variable only capable of holding a value of type Time. 45: // Question: Would passing by reference solve this problem? 46: // Answer: See TIMEVF.CPP. 48: return 0; 49: }