//That's a good and easy example of polymorphism
#include <iostream>
using namespace std;
class Addition {
public:
int ADD(int X,int Y) // Function with parameter
{
return X+Y; // this function is performing addition of two Integer value
}
int ADD() { // Function with same name but without parameter
string a= "HELLO";
string b="SAM"; // in this function concatenation is performed
string c= a+b;
cout<<c<<endl;
}
};
int main(void) {
Addition obj; // Object is created
cout<<obj.ADD(128, 15)<<endl; //first method is called
obj.ADD(); // second method is called
return 0;
}
#include <iostream>
class Animal {
public:
void action() {
std::cout << "The animal does something.
";
}
};
class Fish: public Animal {
public:
void action() {
std::cout << "Fish swim.
";
}
};
class Bird: public Animal {
public:
void action() {
std::cout << "Birds fly.
";
}
};
int main() {
Animal newAnimal;
Fish newFish;
Bird newBird;
newAnimal.action();
newFish.action();
newBird.action();
return 0;
}
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound
" ;
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow
" ;
}
};
int main() {
Animal myAnimal;
Dog myDog;
myAnimal.animalSound();
myDog.animalSound();
return 0;
}
Polymorphism in C++ means, the same entity (function or object) behaves differently in different scenarios. Consider this example: The “ +” operator in c++ can perform two specific functions at two different scenarios i.e when the “+” operator is used in numbers, it performs addition.
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound
" ;
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee
" ;
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow
" ;
}
};