zooOOP
unknown
c_cpp
a year ago
2.0 kB
1
Indexable
Never
#include <iostream> #include <vector> #include <string> // Base class for animals: class Animal { protected: std::string name; int age; public: Animal(std::string n, int a) : name(n), age(a) {} virtual void makeSound() const { std::cout << "Animal sound" << std::endl; } void showInfo() const { std::cout << "Name: " << name << ", Age: " << age; } }; // Derived classes for specific types of animals: class Lion : public Animal { public: Lion(std::string n, int a) : Animal(n, a) {} void makeSound() const override { std::cout << "Roar!"; } }; class Elephant : public Animal { public: Elephant(std::string n, int a) : Animal(n, a) {} void makeSound() const override { std::cout << "Trumpet!"; } }; class Penguin : public Animal { public: Penguin(std::string n, int a) : Animal(n, a) {} void makeSound() const override { std::cout << "Squeak!"; } }; // Zoo class to manage animals: class Zoo { private: static const int MAX_ANIMALS = 100; std::vector<Animal*> animals; public: Zoo() { animals.reserve(MAX_ANIMALS); // reserve space for efficiency } void addAnimal(Animal* animal) { if (animals.size() < MAX_ANIMALS) { animals.push_back(animal); } else { std::cout << "Zoo is full!" << std::endl; } } void showAllAnimals() const { for (const auto& animal : animals) { animal->showInfo(); std::cout << " - "; animal->makeSound(); std::cout << std::endl; } } }; // Testing the code: int main() { Zoo zoo; Lion lion("Leo", 5); Elephant elephant("Dumbo", 10); Penguin penguin("Penny", 2); zoo.addAnimal(&lion); zoo.addAnimal(&elephant); zoo.addAnimal(&penguin); zoo.showAllAnimals(); return 0; }