Sams Teach Yourself C++ in 21 Days

(singke) #1
Implementing Inheritance 377

12


Mammal, assuming that these other classes all use public inheritance. Private inheritance is
discussed on Day 16, “Advanced Inheritance.”
Listing 12.2 demonstrates how to create objects of type Dogand then how to access the
data and methods of that type.

LISTING12.2 Using a Derived Object


1: //Listing 12.2 Using a derived object
2: #include <iostream>
3: using std::cout;
4: using std::endl;
5:
6: enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };
7:
8: class Mammal
9: {
10: public:
11: // constructors
12: Mammal():itsAge(2), itsWeight(5){}
13: ~Mammal(){}
14:
15: //accessors
16: int GetAge() const { return itsAge; }
17: void SetAge(int age) { itsAge = age; }
18: int GetWeight() const { return itsWeight; }
19: void SetWeight(int weight) { itsWeight = weight; }
20:
21: //Other methods
22: void Speak()const { cout << “Mammal sound!\n”; }
23: void Sleep()const { cout << “shhh. I’m sleeping.\n”; }
24:
25: protected:
26: int itsAge;
27: int itsWeight;
28: };
29:
30: class Dog : public Mammal
31: {
32: public:
33:
34: // Constructors
35: Dog():itsBreed(GOLDEN){}
36: ~Dog(){}
37:
38: // Accessors
39: BREED GetBreed() const { return itsBreed; }
40: void SetBreed(BREED breed) { itsBreed = breed; }
41:
42: // Other methods
Free download pdf