Challenge: Smart Pointer Zoo
Completed
Keep animals in a vector<unique_ptr<Animal>>. Animal has a name, a virtual string kind() const and a virtual int legs() const. Make Bird (2 legs) and Dog (4 legs). Read n lines like bird Tweety, then print each as Tweety the bird and finally Total legs: X.
Input
n, then n lines: kind name.
Output
One line per animal, then the total.
Example
Input
3 bird Tweety dog Rex bird Polly
Output
Tweety the bird Rex the dog Polly the bird Total legs: 8
Editor
C++
Hints
#include <memory> and use make_unique<Bird>(name).
Loop with for (const auto& a : zoo) and use a->...
Solution explanation
The vector owns the animals; when it is destroyed at the end of main, every animal is deleted automatically.
Show solution
#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;
class Animal {
protected:
string name;
public:
Animal(string n) : name(n) {}
virtual ~Animal() {}
string getName() const { return name; }
virtual string kind() const = 0;
virtual int legs() const = 0;
};
class Bird : public Animal {
public:
Bird(string n) : Animal(n) {}
string kind() const override { return "bird"; }
int legs() const override { return 2; }
};
class Dog : public Animal {
public:
Dog(string n) : Animal(n) {}
string kind() const override { return "dog"; }
int legs() const override { return 4; }
};
int main() {
int n;
cin >> n;
vector<unique_ptr<Animal>> zoo;
for (int i = 0; i < n; i++) {
string kind, name;
cin >> kind >> name;
if (kind == "bird") {
zoo.push_back(make_unique<Bird>(name));
} else {
zoo.push_back(make_unique<Dog>(name));
}
}
int total = 0;
for (const auto& a : zoo) {
cout << a->getName() << " the " << a->kind() << "\n";
total += a->legs();
}
cout << "Total legs: " << total << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module