Listing 12.5 illustrates what happens if the Dogclass overrides the Speak()method in
Mammal. To save room, the accessor functions have been left out of these classes.
LISTING12.5 Overriding a Base Class Method in a Derived Class
1: //Listing 12.5 Overriding a base class method in a derived class
2: #include <iostream>
3: using std::cout;
4:
5: enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };
6:
7: class Mammal
8: {
9: public:
10: // constructors
11: Mammal() { cout << “Mammal constructor...\n”; }
12: ~Mammal() { cout << “Mammal destructor...\n”; }
13:
14: //Other methods
15: void Speak()const { cout << “Mammal sound!\n”; }
16: void Sleep()const { cout << “shhh. I’m sleeping.\n”; }
17:
18: protected:
19: int itsAge;
20: int itsWeight;
21: };
22:
23: class Dog : public Mammal
24: {
25: public:
26 // Constructors
27: Dog(){ cout << “Dog constructor...\n”; }
28: ~Dog(){ cout << “Dog destructor...\n”; }
29:
30: // Other methods
31: void WagTail() const { cout << “Tail wagging...\n”; }
32: void BegForFood() const { cout << “Begging for food...\n”; }
33: void Speak() const { cout << “Woof!\n”; }
34:
35: private:
36: BREED itsBreed;
37: };
38:
39: int main()
40: {
41: Mammal bigAnimal;
42: Dog Fido;
43: bigAnimal.Speak();
44: Fido.Speak();
45: return 0;
46: }
386 Day 12