Base and Derived
Completed
Write class Animal with a name and a virtual string sound() const returning ..., and Dog and Cat overriding it. Read animals and print NAME says SOUND through an Animal&.
Input
n, then lines dog|cat|animal NAME.
Output
n lines.
Example
Input
3 dog Rex cat Tom animal Blob
Output
Rex says woof Tom says meow Blob says ...
Editor
C++
Hints
virtual lets the call pick the derived version at runtime.
Base classes with virtual functions need a virtual destructor.
Solution explanation
using Animal::Animal; inherits the base constructor; override asks the compiler to check you really override.
Show solution
#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;
class Animal {
public:
explicit Animal(string name) : name_(name) {}
virtual ~Animal() = default;
virtual string sound() const { return "..."; }
const string &name() const { return name_; }
private:
string name_;
};
class Dog : public Animal {
public:
using Animal::Animal;
string sound() const override { return "woof"; }
};
class Cat : public Animal {
public:
using Animal::Animal;
string sound() const override { return "meow"; }
};
void describe(const Animal &a) { cout << a.name() << " says " << a.sound() << "\n"; }
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 == "dog") zoo.push_back(make_unique<Dog>(name));
else if (kind == "cat") zoo.push_back(make_unique<Cat>(name));
else zoo.push_back(make_unique<Animal>(name));
}
for (const auto &a : zoo) describe(*a);
return 0;
}