Learn Computer Programming Free from our source codes in my website.
Sponsored Link Please Support
https://www.techseries.dev/a/27966/qWm8FwLb
https://www.techseries.dev/a/19181/qWm8FwLb
My Personal Website is http://www.jakerpomperada.com
Email me at jakerpomperada@gmail.com and jakerpomperada@yahoo.com
Monday, October 7, 2024
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;
}