|
|
|
|
|
|
|
On line 51 a Dog is declared, Fido. Fido inherits all the attributes of a Mammal, as well as all the attributes of a Dog. Thus Fido knows how to WagTail(), but also knows how to Speak() and Sleep(). |
|
|
|
|
|
|
|
|
Constructors and Destructors |
|
|
|
|
|
|
|
|
Dog objects are Mammal objects. This is the essence of the is-a relationship. When Fido is created, his base constructor is called first, creating a Mammal. Then the Dog constructor is called, completing the construction of the Dog object. Because we gave Fido no parameters, the default constructor was called in each case. Fido doesn't exist until he is completely constructed, which means that both his Mammal part and his Dog part must be constructed. Thus, both constructors must be called. |
|
|
|
|
|
|
|
|
When Fido is destroyed, first the Dog destructor will be called and then the destructor for the Mammal part of Fido. Each destructor is given an opportunity to clean up after its own part of Fido. Remember, to clean up after your Dog! Listing 16.3 demonstrates this. |
|
|
|
|
|
|
|
|
LISTING 16.3 CONSTRUCTORS AND DESTRUCTORS CALLED |
|
|
|
 |
|
|
|
|
1: //Listing 16.3 Constructors and destructors called.
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();
12:
13: //accessors
14: int GetAge() const { return itsAge; }
15: void SetAge(int age) { itsAge = age; }
16: int GetWeight() const { return itsWeight; }
17: void SetWeight(int weight) { itsWeight = weight; }
18:
19: //Other methods
20: void Speak() const { cout << Mammal sound!\n; }
21: void Sleep() const { cout << shhh. I'm sleeping.\n; }
22:
23:
24: protected:
25: int itsAge;
26: int itsWeight;
27: }; |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|