Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

C++ Virtual Functions You are making a program to manage an animal zoo. You have a base class Animal , and two subclasses: Dog and

C++

Virtual Functions

You are making a program to manage an animal zoo. You have a base class Animal, and two subclasses: Dog and Cat. In main, you have an array of Animal pointers, where each pointer can hold a Dog or a Cat. The code loops through the array and calls the speak() method of the object, irrespective of its type. Complete the code by adding the speak() method to the Animal class, so that the code works and the corresponding methods get called correctly.

This is an example of polymorphism in action: without knowing the subtype of the objects, you are able to call the speak() method, and the corresponding implementation is getting executed.

#include

using namespace std;

class Animal

{

public:

string name;

//your code goes here

};

class Dog: public Animal

{

public:

void speak() {

cout <<"Woof!"<

}

};

class Cat: public Animal

{

public:

void speak() {

cout <<"Meaw!"<

}

};

int main() {

Cat c1;

c1.name = "Fluffy";

Dog d1;

d1.name = "Bingo";

Animal *a1 = &c1;

Animal *a2 = &d1;

Animal* arr[] = {a1, a2};

for(int i=0;i<2;i++){

arr[i]->speak();

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Sams Teach Yourself Beginning Databases In 24 Hours

Authors: Ryan Stephens, Ron Plew

1st Edition

067232492X, 978-0672324925

More Books

Students also viewed these Databases questions