Note: I am coding in C++ Consider an animal shelter that contains two types of a
ID: 3824890 • Letter: N
Question
Note: I am coding in C++
Consider an animal shelter that contains two types of animals: dogs and cats. A dog is represented by the Dog class, a cat is represented by a cat class, and both classes inherit the Animal class. The animal shelter maintains a singly list of all the animals (nodes with an Animal * pointer that points to the Animal) When you want to adopt an animal from this shelter, you let them know your preference for a dog, cat, or either. Based on your preference, you adopt the animal closest to the head of the list that matches your preference. In the List class, complete the adoptCat, adoptDog, and adoptAny member function in list.cpp. Each of these functions must: 1. find the animal closest to the head of the list that meets the function preferences (if a suitable animal exists), 2. remove that node from the list, and 3. return a pointer to the Animal (if a suitable animal was found) or NULL if no animal was found Reference The List class (list.cpp, list.h) stores a singly linked list of ListNode nodes, using the same structure and variable names as MP3. The Animal class has a member function getType() that will return "Dog" or "Cat" based on the type of animal. Compile and Test A complete Makefile and tester code is provided for you. To compile and test, run: make ./animal-testExplanation / Answer
or
#include <cstdlib>
#include <typeinfo>
#include <ctime>
#include <iostream>
#include <list>
class Animal
{
public:
virtual ~Animal() = 0 ;
};
Animal::~Animal() {}
class Cat : public Animal
{
};
class Dog : public Animal
{
};
typedef std::list<Animal*> list_type;
void displayTypes(list_type::iterator beg, list_type::iterator end)
{
while (beg != end)
{
Animal* value = *beg++;
if (typeid(*value) == typeid(Cat))
std::cout << "Cat";
else if (typeid(*value) == typeid(Dog))
std::cout << "Dog";
else if (typeid(*value) == typeid(Animal))
std::cout << "Animal"; // This should never happen!
else
std::cout << "Unknown";
std::cout << ' ';
}
}
int main()
{
std::srand(std::time(0));
list_type list;
for (unsigned i = 0; i < 10; ++i)
list.push_back((rand() % 2 ? (Animal*)new Cat : (Animal*)new Dog));
displayTypes(std::begin(list), std::end(list));
while (!list.empty())
{
delete list.back();
list.pop_back();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.