C++ Polymorphism

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this C++ tutorial, let us have a look at Polymorphism, its implementation and sample C++ program for polymorphism.

Introduction of Polymorphism

Polymorphism refers to having more than one form. So, polymorphism means multiple forms of something. A real-life example of polymorphism is, a person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee. So the same person posses different behaviour in different situations.

Implementation of Polymorphism

In C++, polymorphism is implemented through:

  • Methods Overloading
  • Constructor Overloading
  • Operator Overloading
  • Virtual Function

Methods Overloading

Two or more methods with the same name but different number or type of arguments are known as method overloading. The return type of the function has no impact on method overloading. When the call to such a function is made, the compiler matches the function call with the function having the same number and type of arguments.

Program for Method overloading in C++

#include<iostream.h>
#include<conio.h>
class shape
{
public:
void area(int x, int y)
{
cout<<"\nArea of Rectangle ="<<x*y;
}
void area(int x)
cout<<"\nArea of square ="<<x*x;
}
void area(float x, float y)
{
cout<<"\nArea of Cylinder = "3.14 * x * x * y;
}
void area(float x)
{
cout<<"\nArea of Circle = "<< 3.14 * x * x;
}
};
void main()
{
clrscr();
shape sh;
sh.area(3);
sh.area(4.6f);
sh.area(12,45);
sh.area(5.6f,7.8f);
}

Output

Area of Square = 9
Area of Circle = 66.442397
Area of Rectangle = 540
Area of Cylinder = 768.069113

Constructor Overloading

Constructors are called whenever an object is instantiated. The name of the constructor is the same as that of the class in which it is defined. A class may have more than one constructor. Whenever a class has multiple constructors, they are implemented as overloaded methods. Whenever a class has more than one constructor, each constructor must have a different number or type of parameters. This is known as Constructor Overloading.

Program for Constructor Overloading in C++

#include<iostream>
#include<conio.h>
using namespace std;
class Example {
// Variable Declaration
int a, b;
public:
//Constructor wuithout Argument
Example() {
// Assign Values In Constructor
a = 50;
b = 100;
cout << "\nIm Constructor";
}
//Constructor with Argument
Example(int x, int y) {
// Assign Values In Constructor
a = x;
b = y;
cout << "\nIm Constructor";
}
void Display() {
cout << "\nValues :" << a << "\t" << b;
}
};
int main() {
Example Object(10, 20);
Example Object2;
// Constructor invoked.
Object.Display();
Object2.Display();
// Wait For Output Screen
getch();
return 0;
}

Output

Im Constructor 
Im Constructor 
Values :10 20 
Values :50 100

Leave a Comment

Your email address will not be published. Required fields are marked *