Function Overloading
Function Overloading
If multiple functions having same name but parameters of the functions should be different is known
as Function Overloading.
If we have to perform only one operation and having same name of the functions increases the
readability of the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the function such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it
may be difficult for you to understand the behavior of the function because its name differs.
Parameters should be different means
1. Data Type of parameter should be different
Eg:
void add(int, int);
void add(double,double);
main()
{
add(10,2);
add(5.3,6.2);
return 0;
}
1
2. Number of parameter should be different
Eg:
void add(int , int);
void add(int , int, int);
#include<iostream>
using namespace std;
main()
{
add(10,2);
add(5,6,4);
return 0;
}
2
#include<iostream>
using namespace std;
main()
{
add(10,2.5);
add(5.5,6);
return 0;
}
Eg:
void add(int , int); function overloading does not depend onto the return type
int add(int, int); of the method
3
Q: Write a in C++ program to find volume of cube, cylinder and rectangular box using
the concept of function overloading.
Volume of cube=s3; volume of cylinder=pi*r2h; and volume of rectangular box=l*b*h
#include<iostream>
using namespace std;
float vol(int,int);
float vol(float);
int main()
{
int r,h,a;
float r1;
cout<<"Enter radius and height of a cylinder:";
cin>>r>>h;
cout<<"Enter side of cube:";
cin>>a;
cout<<"Enter radius of sphere: ";
cin>>r1;
cout<<"Volume of cylinder is "<<vol(r,h);
cout<<"\nVolume of cube is "<<vol(a);
return 0;
}
float vol(int r,int h)
{
return(3.14*r*r*h);
}
int vol(int a)
{
4
return(a*a*a);
}
Q: Write a class Volume in C++ program to find volume of cube, cylinder and
rectangular box using the concept of function overloading.
Volume of cube=s3; volume of cylinder=pi*r2h; and volume of rectangular box=l*b*h
Q: Write a class Draw in C++ program with three draw functions using the concept of
function overloading. The output of that draw method should be as follows:
draw() draw(int) draw(int,char)
*
* *
* * *
* * * *
A
A A
A A A
A A A A