43: void WagTail() const { cout << “Tail wagging...\n”; }
44: void BegForFood() const { cout << “Begging for food...\n”; }
45:
46: private:
47: BREED itsBreed;
48: };
49:
50: int main()
51: {
52: Dog Fido;
53: Fido.Speak();
54: Fido.WagTail();
55: cout << “Fido is “ << Fido.GetAge() << “ years old” << endl;
56: return 0;
57: }
Mammal sound!
Tail wagging...
Fido is 2 years old
On lines 8–28, the Mammalclass is declared (all its functions are inline to save
space here). On lines 30–48, the Dogclass is declared as a derived class of
Mammal. Thus, by these declarations, all Dogshave an age, a weight, and a breed. As
stated before, the age and weight come from the base class,Mammal.
On line 52, a Dogis declared:Fido. Fidoinherits all the attributes of a Mammal, as well as
all the attributes of a Dog. Thus,Fidoknows how to WagTail(), but he also knows how
to Speak()and Sleep(). On lines 53 and 54,Fidocalls two of these methods from the
Mammalbase class. On line 55, the GetAge()accessor method from the base class is also
called successfully.
Inheritance with Constructors and Destructors ..................................................
Dogobjects are Mammalobjects. This is the essence of the is-a relationship.
When Fidois created, his base constructor is called first, creating a Mammal. Then, the
Dogconstructor is called, completing the construction of theDogobject. Because Fidois
given no parameters, the default constructor was called in each case. Fidodoesn’t exist
until he is completely constructed, which means that both his Mammalpart and his Dog
part must be constructed. Thus, both constructors must be called.
OUTPUT
378 Day 12
LISTING12.2 continued
ANALYSIS