
Let’s understand the function Overloading concept of C++
What is Function Overloading?
In C++, you can define two or more functions with same name but with a different argument. This concept is known as Function Overloading.
Function Overloading Example:
#include<iostream>
#include<conio.h>
using namespace std
#define pi 3.14
float area(float r); //THIS IS FOR AREA OF CIRCLE
float area(int); // FOR AREA OF SQUARE
float area(float l,float b); //FOR AREA OF RECTANGLE
void main()
{
float r,b,ac,as,ar;
int l;
cout<<“Enter radius of circle : “;
cin>> r;
ac=area(r);
cout<<“Area of circle = “<<ac<<endl;
cout<<“Enter length of square : “;
cin>>l;
as=area(l);
cout<<“Area of sqaure = “<<as<<endl;
cout<<“Enter length and breath of rectangle : “;
cin>>l>>b;
ar=area(l,b);
cout<<“Area of rectangle = “<<ar<<endl;
getch();
}
float area(float r)
{
float a;
a=pi*r*r;
return a;
}
float area(int l)
{
float a;
a=l*l;
return a;
}
float area(float l,float b)
{
float a;
a=l*b;
return a;
}
#include<conio.h>
using namespace std
#define pi 3.14
float area(float r); //THIS IS FOR AREA OF CIRCLE
float area(int); // FOR AREA OF SQUARE
float area(float l,float b); //FOR AREA OF RECTANGLE
void main()
{
float r,b,ac,as,ar;
int l;
cout<<“Enter radius of circle : “;
cin>> r;
ac=area(r);
cout<<“Area of circle = “<<ac<<endl;
cout<<“Enter length of square : “;
cin>>l;
as=area(l);
cout<<“Area of sqaure = “<<as<<endl;
cout<<“Enter length and breath of rectangle : “;
cin>>l>>b;
ar=area(l,b);
cout<<“Area of rectangle = “<<ar<<endl;
getch();
}
float area(float r)
{
float a;
a=pi*r*r;
return a;
}
float area(int l)
{
float a;
a=l*l;
return a;
}
float area(float l,float b)
{
float a;
a=l*b;
return a;
}
Here, ‘area’ function is repeated three times with different method and argument. It is on the argument you pass from the main function. If you pass only ‘int l’ in the function argument ‘area(l);’ then it will execute the function with one int argument and so on.
Why Function Overloading?
If you make a program to find area of shapes like circle, square, rectangle etc or a program like this, instead of declaring functions like areaofcircle(); areaofsqaure(); or areaofrectangle(); its better to declare just one function area(); with different argument and definition and make the execution similar and uniform.
How to use function Overloading?
As I shown you an example of function Overloading above, here is a syntax of function Overloading:
<return-type> FunctionName(<data-type> VariableName);
Here you can differ the argument as you make different forms of that functions.
Notes:
- It’s important to declare the function with different argument as it will help the compiler to identify when to call which function.
- Function Overloading is a type of Static Polymorphism, as it creates many form of a single function and even identifies it at compile time.
Thanks for reading!
StayTunedForMore();