|
|
|
|
|
|
|
Mammal constructor
Dog constructor
Mammal sound!
Tail wagging
Fido is 1 years old
Dog destructor
Mammal destructor
|
|
|
|
|
|
|
|
|
Analysis: Listing 16.3 is just like Listing 16.2, except that the constructors and destructors now print to the screen when called. Mammal's constructor is called, and then Dog's. At that point the Dog fully exists, and its methods can be called. When Fido goes out of scope, Dog's destructor is called, followed by a call to Mammal's destructor. |
|
|
|
|
|
|
|
|
Passing Arguments to Base Constructors |
|
|
|
|
|
|
|
|
It is possible that you'll want to overload the constructor of Mammal to take a specific age, and that you'll want to overload the Dog constructor to take a breed. How do you get the age and weight parameters 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 16.4 demonstrates this. |
|
|
|
|
|
|
|
|
LISTING 16.4 OVERLOADING CONSTRUCTORS IN DERIVED CLASSES |
|
|
|
 |
|
|
|
|
1: //Listing 16.4 Overloading constructors in derived classes
2:
3: #include <iostream.h>
4: enum BREED { YORKIE, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB };
5:
6: class Mammal
7: {
8: public:
9: // constructors
10: Mammal();
11: Mammal(int age);
12: ~Mammal();
13:
14: //accessors
15: int GetAge() const { return itsAge; }
16: void SetAge(int age) { itsAge = age; }
17: int GetWeight() const { return itsWeight; }
18: void SetWeight(int weight) { itsWeight = weight; }
19:
20: //Other methods
21: void Speak() const { cout << Mammal sound!\n; } |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|