One call, many behaviours: the classic first example of polymorphism.
What to build
An Animal base class with Dog, Cat and Cow classes that each supply their own sound.
Requirements
- Make
sound()virtual, and override it in each derived class. - Call
speak()through anAnimal*. - Give
Animala virtual destructor, and delete every animal you create.
Input
The first line has q. Each of the next q lines has a kind (dog, cat or cow) and a name.
Output
One line per animal: NAME says SOUND, where the sounds are Woof, Meow and Moo.
Constraints
1 ≤ q ≤ 100, and names are one word.
Example
Input:
3
dog Rex
cat Tom
cow Daisy
Output:
Rex says Woof
Tom says Meow
Daisy says Moo
Why it works
speak() is written once in the base class, and the virtual call to sound() inside it picks the version for the real animal while the program runs.
Examples
Example 1 · Input
3 dog Rex cat Tom cow Daisy
Expected output
Rex says Woof Tom says Meow Daisy says Moo
Example 2 · Input
1 cat Mini
Expected output
Mini says Meow
Hints
Hint 1
Give `Animal` a pure virtual `string sound() const`, and a `speak()` that prints the name, `says` and the sound.
Hint 2
Create each animal with `new`, keep it as an `Animal*`, and delete it after it speaks.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
using namespace std;
class Animal {
protected:
string name;
public:
Animal(string n) : name(n) {}
virtual ~Animal() {}
virtual string sound() const = 0;
void speak() const {
cout << name << " says " << sound() << endl;
}
};
class Dog : public Animal {
public:
Dog(string n) : Animal(n) {}
string sound() const override { return "Woof"; }
};
class Cat : public Animal {
public:
Cat(string n) : Animal(n) {}
string sound() const override { return "Meow"; }
};
class Cow : public Animal {
public:
Cow(string n) : Animal(n) {}
string sound() const override { return "Moo"; }
};
int main() {
int q;
cin >> q;
while (q-- > 0) {
string kind, name;
cin >> kind >> name;
Animal* a;
if (kind == "dog") a = new Dog(name);
else if (kind == "cat") a = new Cat(name);
else a = new Cow(name);
a->speak();
delete a;
}
return 0;
}