Challenge: Animal Chorus
Completed
Write a base class Animal with a virtual string sound() const, and children Dog (Woof), Cat (Meow) and Cow (Moo). Read a line of animal names and print all their sounds on one line, separated by spaces.
Input
n, then n words (dog, cat or cow).
Output
The sounds, like Woof Meow Woof.
Example
Input
3 dog cat dog
Output
Woof Meow Woof
Editor
C++
Hints
Make one object of each kind, and a const Animal* that you point at the right one.
Calling a->sound() runs the child's version because sound() is virtual.
Solution explanation
The pointer's type is Animal*, but because sound() is virtual, the real object decides what is returned.
Show solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Animal {
public:
virtual string sound() const { return "..."; }
virtual ~Animal() {}
};
class Dog : public Animal {
public:
string sound() const override { return "Woof"; }
};
class Cat : public Animal {
public:
string sound() const override { return "Meow"; }
};
class Cow : public Animal {
public:
string sound() const override { return "Moo"; }
};
int main() {
int n;
cin >> n;
Dog dog;
Cat cat;
Cow cow;
for (int i = 0; i < n; i++) {
string word;
cin >> word;
const Animal* a = &dog;
if (word == "cat") a = &cat;
if (word == "cow") a = &cow;
if (i > 0) cout << " ";
cout << a->sound();
}
cout << "\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