Polymorphism
Polymorphism
Unit 3
Polymorphism
• The word “polymorphism” means having many forms.
• When there are multiple functions with the same name but
different parameters, then the functions are said to
be overloaded, hence this is known as Function Overloading.
• Functions can be overloaded by changing the number of
arguments or/and changing the type of arguments.
• In simple terms, it is a feature of object-oriented programming
providing many functions that have the same name but distinct
parameters when numerous tasks are listed under one function
name.
• There are certain Rules of Function Overloading that should
be followed while overloading a function.
C++ program to demonstrate function overloading or Compile-time Polymorphism
#include <iostream>
using namespace std;
class Geeks {
public:
void func(int x)
{
cout << "value of x is " << x << endl;
}
int main()
{
Geeks obj1;
obj1.func(7);
obj1.func(9.132);
obj1.func(85, 64);
return 0;
}
Operator Overloading
• For example, we can make use of the addition operator (+) for
string class to concatenate two strings.
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// This is automatically called when '+' is used with between two Complex objects
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
}
Runtime Polymorphism