Function Overloading
Function Overloading is a feature in C++ where two or more functions can have the same name but different parameters. Function overloading can be considered as an example of polymorphism feature in C++.Function overloading can also be called as method overloading and Function overloading can be considered as static or compile-time polymorphism.
Let us take an example program for better understanding.
Function Overloading in C++ : example 1
{ public:
void sum(int a, int b)
{ cout<<"a+b:"<<a+b;
}
void sum(int a,int b,int c)
{
cout<<"a+b+c:"<<a+b+c;
}
}
int main()
{
Addition ob;
ob.sum(5,4);
cout<<endl;
ob.sum(4,5,6);
}
from the above example, you can see that I have created two functions with the same name as a sum and used different arguments. In the first function, it will take two arguments and three arguments for the second function. So the output of the program will be:
a+b: 9
a+b+c: 15
Here we have an example Program to demonstrate function overloading in C++. In the below program, area() function is overloaded to calculate the area of a trapezium, rectangle, and circle using Function Overloading.
Function Overloading in C++
#Example 2:
#include<iostream>using namespace std;
template<class T>
T area(T radius)
{
return (22*radius*radius/7);}
template<class T>
T area(T length, T breadth)
{
return (length*breadth);
}
template<class T>
T area(T side1, T side2, T height)
{
return ((side2+side1)/2*height);
}
int main()
{
double r,b,l,s1,s2,h;
cout<<“Enter the radius of circle: “;
cin>>r;
cout<<“Area : “<<area(r)<<endl;
cout<<“Enter the length and breadth of Rectangle: “;
cin>>l>>b;
cout<<“Area : “<<area(l,b)<<endl;
cout<<“Enter the parallel side and height of Trapezium: “;
cin>>s1>>s2>>h;
cout<<“Area : “<<area(s1,s2,h)<<endl;
return 0;
}
OUTPUT:
Enter the radius of circle: 14
Area: 616
Enter the length and breadth of Rectangle: 2 5
Area: 10
Enter the parallel side and height of Trapezium: 14 6 3
Area: 30
You must be also searching for these programming languages :
tags: Function Overloading, function overloading in C++, function overloading C++, function overloading in C++ example.