Virtual function - Zoo

Virtual function Zoo

Expand on the previous zoo example by creating a base class Animal with a virtual method make_sound(). Create derived classes Lion, Elephant, and Monkey, each overriding the make_sound() method to output their respective sounds. Store these animals in a std::vector<Animal*> and iterate over the vector, calling make_sound() on each animal. Demonstrate that each animal correctly makes its unique sound, even when called from a Animal pointer.

Answer

#include <iostream>
#include <vector>

class Animal {
public:
    virtual void make_sound() {
        std::cout << "Some generic animal sound." << std::endl;
    }
};

class Lion : public Animal {
public:
    void make_sound() override {
        std::cout << "Roar!" << std::endl;
    }
};

class Elephant : public Animal {
public:
    void make_sound() override {
        std::cout << "Trumpet!" << std::endl;
    }
};

class Monkey : public Animal {
public:
    void make_sound() override {
        std::cout << "Ooh ooh aah aah!" << std::endl;
    }
};

int main() {
    std::vector<Animal*> zoo;
    zoo.push_back(new Lion());
    zoo.push_back(new Elephant());
    zoo.push_back(new Monkey());

    for (Animal* animal : zoo) {
        animal->make_sound();  // Calls the correct make_sound() method for each animal
    }

    // Clean up memory
    for (Animal* animal : zoo) {
        delete animal;
    }

    return 0;
}
Questions