Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Suppose we have a class hierarchy of animals where the classes are Animal, Cat,

ID: 3905359 • Letter: S

Question

Suppose we have a class hierarchy of animals where the classes are Animal, Cat, TabbyCat, Dog and Chihuahua.

All the classes have or inherit the function makeSound() which will output a “sound” to the console.

Animals never make any sound so makeSound() will be a pure virtual function in the Animal class. Cat and Dog are derived from Animal and override makeSound().

TabbyCat is derived from Cat and inherits makeSound(). Chihuahua is derived from Dog and overrides makeSound()with code that calls the makeSound() from Dog then outputs “Yap Yap”.

a. Write the prototype for the Animal::makeSound() function.

b. Write the implementation for the Chihuahua::makeSound() function.

c. Illustrate dynamic binding by making an array of Animalpointers of size 4 and pointing its elements to objects of each type of Animal (Dog, Cat, TabbyCat, Chihuahua).

Then loop through the array and call makeSound() for each element.

Explanation / Answer

#include <iostream>
using namespace std;

class Animal // base class
{

public:
virtual void makeSound()=0; // pure virtual function
};
class Cat : public Animal
{

public:
void makeSound();

};
void Cat::makeSound()
{
cout<<" Mew Mew";
}
class TabbyCat : public Cat
{
public:
void makeSound();

};
void TabbyCat::makeSound()
{
cout<<" Mew ";
}
class Dog : public Animal
{

public:
void makeSound();

};
void Dog::makeSound()
{
cout<<" Bow Wow";
}
class Chihuahua : public Dog
{

public:
void makeSound();


};
void Chihuahua::makeSound()
{
cout<<" Yap Yap";
}
int main() {

Animal *animalPtr[4]; // array of 4 pointers of type Animal

// assign base class pointers to derived class objects
animalPtr[0] = new Cat();
animalPtr[1] = new TabbyCat();
animalPtr[2] = new Dog();
animalPtr[3] = new Chihuahua();

for(int i=0;i<4;i++)
animalPtr[i]->makeSound(); // call function makeSound() using pointers
return 0;
}

Output:

Mew Mew
Mew
Bow Wow
Yap Yap

Do ask if any doubt. Please upvote.