Implementing Inheritance 381
12
When Fidogoes out of scope,Dog’s destructor is called, followed by a call to Mammal’s
destructor. You see that this is confirmed in the output from the listing.
Passing Arguments to Base Constructors ......................................................
It is possible that you will want to initialize values in a base constructor. For example,
you might want to overload the constructor of Mammalto take a specific age, and want to
overload the Dogconstructor to take a breed. How do you get the age and weight parame-
ters passed up to the right constructor in Mammal? What if Dogs want to initialize weight
but Mammals don’t?
Base class initialization can be performed during class initialization by writing the base
class name, followed by the parameters expected by the base class. Listing 12.4 demon-
strates this.
LISTING12.4 Overloading Constructors in Derived Classes
1: //Listing 12.4 Overloading constructors in derived classes
2: #include <iostream>
3: using namespace std;
4:
5: enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };
6:
7: class Mammal
8: {
9: public:
10: // constructors
11: Mammal();
12: Mammal(int age);
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:
26: protected:
27: int itsAge;
28: int itsWeight;
29: };
30:
31: class Dog : public Mammal