1: // Filename: TIMEVF.CPP
2: // iurpose: Illustrates the "static binding" problem that
3: // prevents "passing by reference" from solving
4: // the "slicing problem" we had in TIMESLIC.CPP.
6: #include <iostream>
7: using namespace std;
9: #include "TIME.H"
10: #include "ZONETIME.H"
13: void DisplayTimeWithBanner(/* in */ Time& someTime)
14: // Pre: someTime contains a Time object or an object of a derived class.
15: // Post: The value in someTime has been displayed in "banner form".
16: {
17: cout << "***************************" << endl;
18: cout << "** The time is ";
19: someTime.Display();
20: cout << endl;
21: cout << "***************************" << endl << endl;
22: }
25: int main()
26: {
27: Time myTime(8, 30, 0);
28: ZoneTime yourTime(10, 45, 0, CST);
30: cout << endl;
31: DisplayTimeWithBanner(myTime);
32: // This call continues to work as before, as expected.
34: DisplayTimeWithBanner(yourTime);
35: // The hoped-for improvement does not happen, and once again
36: // we do not get the time zone part of the ZoneTime object
37: // printed out. The reason is that even though no "slicing"
38: // takes place this time (because of the passing by reference)
39: // the compiler still has to decide *at compile-time* which
40: // Display() function is going to be used. Because the parameter
41: // being passed is of type Time and "static binding" is used,
42: // the Display() from the Time class is chosen.
44: // Question: What to do?
45: // Answer: Go back to the Time class specification file and
46: // make the Display() function a "virtual function"
47: // by placing the keyword "virtual" in front of its
48: // prototype. This tells the compiler to insert the
49: // necessary code to allow the decision to be made at
50: // run-time as to which version of Display() will be.
51: // called. This solves our problem.
53: return 0;
54: }