-
Notifications
You must be signed in to change notification settings - Fork 0
/
bonus_exercise.cpp
52 lines (47 loc) · 1.05 KB
/
bonus_exercise.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <memory>
#include <vector>
class Animal {
public:
virtual ~Animal() {}
virtual void makeSound() = 0;
};
class Dog : public Animal {
public:
void makeSound() override {
std::cout << "Woof!\n";
}
};
class Cat : public Animal {
public:
void makeSound() override {
std::cout << "Meow!\n";
}
};
class Zoo {
private:
std::vector<std::unique_ptr<Animal>> animals;
public:
void addAnimal(std::unique_ptr<Animal> animal) {
animals.push_back(std::move(animal));
}
void makeSounds() {
for (const auto& animal : animals) {
animal->makeSound();
}
}
void removeAnimal(int index) { // New method to remove an animal
if (index < 0 || index >= animals.size()) {
std::cout << "Index out of range\n";
return;
}
animals.erase(animals.begin() + index);
}
};
int main() {
Zoo zoo;
zoo.addAnimal(std::make_unique<Dog>());
zoo.addAnimal(std::make_unique<Cat>());
zoo.makeSounds();
return 0;
}