Handout 4 - Public Derived Class

1    // Public derived class example
2
3    /* C++ allows you to derive a class from one or more base classes. A
4       derived class inherits all members of its base class. Access privileges of
5       inherited members can be changed by the derived class through access
6       specifiers that prefix the declaration of the base class. Valid access
7       specifiers are public and private.
8     */
9
10   #include <string.h>
11   #include <iostream.h>
12
13   // ****** Clown Class Definitions ******
14
15   class Clown {
16     public:
17       void set_nose(char *);
18       void show_nose();
19     private:
20       char nose[10];
21   };
22
23   void Clown::set_nose(char * in_nose) {
24     strcpy(nose,in_nose);
25   }
26
27   void Clown::show_nose() {
28     cout << nose;
29   }
30
31   // ****** Bozo Class Definitions (derived from Clown) ******
32
33   class Bozo : public Clown {
34     public:
35       void set_shoe(float);
36       void show_shoe();
37     private:
38       char nose[20];         // note redefinition of nose
39       float shoe_size;  
40   };
41
42   void Bozo::set_shoe(float in_shoe) {
43     shoe_size = in_shoe;
44   }
45
46   void Bozo::show_shoe() {
47     cout << shoe_size;
48   }
49
50   // ****** main function ******
51
52   int main() {
53     Clown X;                          // define a Clown
54     Bozo Z;                           // define a Bozo
55     X.set_nose("red");                // give clown X a red nose
56     X.show_nose();                    // show X's nose color
57
58     Z.set_nose("pink");               // give Bozo a pink nose
59     Z.set_shoe(18.5);                 // Bozo has big feet
60     Z.show_nose();                    // show Bozo's nose color
61     Z.show_shoe();                    // show Bozo's shoe size
62
63     return 0;
64   }