Source of timeslice.cpp


  1: /** @file timeslice.cpp
  2: Illustrates the "slicing problem", one of the
  3: problems that virtual functions help to solve.
  4: */

  6: #include <iostream>
  7: using namespace std;

  9: #include "time.h"
 10: #include "zonetime.h"

 12: void DisplayTimeWithBanner
 13: (
 14:     Time someTime //in
 15: )
 16: /**<
 17: Display a time within a simple banner.
 18: @pre  someTime contains a Time object or an object of a derived class.
 19: @post The value in someTime has been displayed in "banner form".
 20: */
 21: {
 22:     cout << "\n***************************";
 23:     cout << "\n** The time is ";
 24:     someTime.display();
 25:     cout << "\n***************************\n";
 26: }


 29: int main()
 30: {
 31:     cout << "\nThis program illustrates the \"slicing problem\".";
 32:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 34:     cout << "\nFirst we declare a Time object."
 35:         "\nThen we display it with a call to DisplayTimeWithBanner().";
 36:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 37:     Time myTime(8, 30, 0);
 38:     DisplayTimeWithBanner(myTime);
 39:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 40:     cout << "\nOutput is what you would expect, since we are passing "
 41:         "\na Time object and that's what the function expects.";
 42:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 44:     cout << "\nNext we declare a ZoneTime object."
 45:         "\nThen we display it with a call to DisplayTimeWithBanner().";
 46:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 47:     ZoneTime yourTime(10, 45, 0, CST);
 48:     DisplayTimeWithBanner(yourTime);
 49:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 50:     cout << "\nOutput is not what you might hope for. This time we are "
 51:         "passing an object of\nclass ZoneTime, which is also a Time object "
 52:         "(any ZoneTime \"is a\" Time, because\nof inheritance), so you "
 53:         "might hope that the value of the ZoneTime object would\nbe printed "
 54:         "out. Unfortunately, the ZoneTime value is \"bigger than\" the "
 55:         "Time\nvalue (occupies more storage space in memory because "
 56:         "of the additional member\nvariable) but the \"extra part\" is "
 57:         "\"sliced off\" as it is passed into the\nDisplayTimeWithBanner() "
 58:         "function because it is passed by value and a copy\nis made to "
 59:         "a local variable only capable of holding a value of type Time.";
 60:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 62:     cout << "\nQuestion: Would passing by reference solve this problem? "
 63:         "\nAnswer:   See timevirtual.cpp.";
 64:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 65: }