Thursday, October 3, 2024

Animals Sound Using Polymorphism in C++

 




Program Listing


#include <iostream>


class Animal {

public:

    virtual void makeSound() {

        std::cout << "The animal makes a sound." << std::endl;

    }

};


class Dog : public Animal {

public:

    void makeSound() override {

        std::cout << "\tThe dog barks." << std::endl;

    }

};



class Snake : public Animal {

public:

    void makeSound() override {

        std::cout << "\tThe snake ssshh." << std::endl;

    }

};


class Cat : public Animal {

public:

    void makeSound() override {

        std::cout << "\tThe cat meows." << std::endl;

    }

};


int main() {

    Animal* animals[3];

    animals[0] = new Dog();

    animals[1] = new Cat();

    animals[2] = new Snake();



 std::cout <<"\n\n\tAnimals Sound Using Polymorphism in C++\n\n";

    for (int i = 0; i < 3; i++) {

        std::cout << "\tAnimal " << i + 1 << ": ";

        animals[i]->makeSound();

    }


    // Don't forget to delete the dynamically allocated objects to free memory.

    for (int i = 0; i < 3; i++) {

        delete animals[i];

    }

std::cout << "\n\tEnd of Program. Thank you for using this program." << std::endl;

    return 0;

}


No comments:

Post a Comment