Pure Animal
Creating a base class Animal with a pure virtual method make_sound(). Add derived classes Dog and Cat that overrides the speak method to output "Woof!" and "Meow!", respectively. Add another derived class Bird that overrides the speak()method to output "Chirp!". Then create a new derived class Parrot that inherits from Bird and overrides the speak() method to output "I'm a parrot!" .Creatie objects of Dog, Cat, Bird and Parrot, and store them in a std::vector<Animal*>.
Take note of how you care unable to create Animal objects.
Hint
Notice that Bird is not an abstract class since it provides a definition for speak(), but Parrot can still override it.
Answer
#include <iostream>
#include <vector>
class Animal {
public:
virtual void speak() = 0; // Pure virtual function
};
class Dog : public Animal {
public:
void speak() override {
std::cout << "Woof!" << std::endl;
}
};
class Cat : public Animal {
public:
void speak() override {
std::cout << "Meow!" << std::endl;
}
};
class Bird : public Animal {
public:
void speak() override {
std::cout << "Chirp!" << std::endl;
}
};
class Parrot : public Bird {
public:
void speak() override {
std::cout << "I'm a parrot!" << std::endl;
}
};
int main() {
std::vector<Animal*> animals;
animals.push_back(new Dog());
animals.push_back(new Cat());
animals.push_back(new Bird());
animals.push_back(new Parrot());
// animals.push_back(new Animal()); // Compilation would not complete
for (Animal* animal : animals) {
animal->speak(); // Calls the appropriate speak() method
}
// Clean up memory
for (Animal* animal : animals) {
delete animal;
}
}