class Base
class Derived1
class Derived2
1: /** inherit4.cpp */
3: #include <iostream>
4: using namespace std;
6: #include "utilities.h"
7: using Scobey::RandomGenerator;
9: class Base
10: {
11: public:
12: int i;
13: Base(int x) { i = x; }
14: virtual void display()
15: {
16: cout << "\nUsing Base version of display(): ";
17: cout << i;
18: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
19: }
20: };
23: class Derived1 : public Base
24: {
25: public:
26: Derived1(int x) : Base(x) {}
27: virtual void display()
28: {
29: cout << "\nUsing Derived1's version of display(): ";
30: cout << 11*i;
31: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
32: }
33: };
36: class Derived2 : public Base
37: {
38: public:
39: Derived2(int x) : Base(x) {}
40: virtual void display()
41: {
42: cout << "\nUsing Derived2's version of display(): ";
43: cout << 2*i;
44: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
45: }
46: };
49: int main()
50: {
51: cout << "\nThis program illustrates how a virtual function can be "
52: "\nused to respond to random events occurring at run time.";
53: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
55: cout << "\nWe generate 10 random objects, each one of which may have "
56: "either of the two\npossible derived types. In each case the "
57: "identically named member function,\ndisplay(), is called, so it "
58: "is up to the virutal function mechanism to see\nthat the correct "
59: "one is used for each object.";
60: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
62: RandomGenerator g;
63: Base *p;
64: for(int i=0; i<10; i++)
65: {
66: int j = g.getNextInt(1, 10);
67: if((j%2 == 1)) //j is odd
68: {
69: Derived1 derived1Object(j);
70: p = &derived1Object; //If odd use a Derived1 object
71: p->display(); //Call Derived1's display() function
72: }
73: else //j is even
74: {
75: Derived2 derived2Object(j);
76: p = &derived2Object; //If even use a Derived2 object
77: p->display(); //Call Derived2's display() function
78: }
79: }
80: }