Polymorphism means "many forms", and it occurs when we have many classes that are related to each other by inheritance but have the same method implemented in different forms.
As we've studied in the previous lesson, inheritance enables derived classes to have the attributes and methods from another class.
Polymorphism uses those methods to perform different tasks. This allows us to perform a single action in different ways.
For example, imagine a base class Animal with a method called makeSound(). Derived classes of Animals could be Pigs, Cats, Dogs, Birds, etc.
Every animal can "make a sound", but each one sounds different:
Pig: wee wee
Dog: woof woof
Bird: tweet tweet
Cat: meow meow
This is polymorphism - the same action (making a sound) behaves differently for each animal:
#include <iostream>
using namespace std;
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: woof woof \n";
}
};
class Cat : public Animal {
public:
void animalSound() {
cout << "The cat says: meow meow \n";
}
};
class Bird : public Animal {
public:
void animalSound() {
cout << "The bird says: tweet tweet \n";
}
};
int main() {
// Write C++ code here
Pig pig;
pig.animalSound();
Dog dog;
dog.animalSound();
Cat cat;
cat.animalSound();
Bird bird;
bird.animalSound();
return 0;
}
As you may have observed, the same method (animalSound) in the derive classes has been implemented differently in each derived classes.