Write a program to find out volume of a cube, cuboid and cylinder using function overloading.
Answers
#include<iostream>
using namespace std;
float vol(int,int);
float vol(float);
int vol(int);
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);
cout<<"\nVolume of sphere is"<<vol(r1);
return 0;
}
float vol(int r,int h)
{
return(3.14*r*r*h);
}
float vol(float r1)
{
return((4*3.14*r1*r1*r1)/3);
}
int vol(int a)
{
return(a*a*a);
}
This is the program to find out volume of a cube, cuboid and cylinder using function overloading.
PLZ MARK ME AS BRAINLIEST.
Answer:
Two or more functions can have the same name but different parameters; such functions are called function overloading.
Explanation:
- In C++, the process of having two or more functions with the same name but differing argument values is referred to as function overloading. Function overloading involves either utilising a different number of parameters or a different kind of arguments to redefine the function. The only way the compiler can distinguish between the functions is through these differences.
- Function overloading has the benefit of improving programme readability by eliminating the need for several names for the same activity.
The easiest way to remember this rule is that the parameters should qualify any one or more than one of the following conditions:
- they should have a different type
- they should have a different number
- they should have a different sequence of parameters.
Examples:
Let's see the simple example of function overloading where we are changing number of arguments of add() method.
// program of function overloading when number of arguments vary.
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Program 1:
#include<iostream>
using namespace std;
int main()
{
int l=0,b=0,h=0,r=0,ch;
cout<<"1.Volume of cube\n2.Volume of cuboid\n3.Volume of cylinder\nEnter choice: ";
cin>>ch;
switch(ch)
{
case 1:cout<<"Length= ";
cin>>l;
cout<<"Volume= "<<volume(l)<<endl;
break;
case 2:cout<<"Length= ";
cin>>l;
cout<<"Breadth= ";
cin>>b;
cout<<"Height= ";
cin>>h;
cout<<"Volume= "<<volume(l,b,h)<<endl;
break;
case 3:cout<<"Radius= ";
cin>>r;
cout<<"Height= ";
cin>>h;
cout<<"Volume= "<<volume(r,h)<<endl;
break;
default:cout<<"Wrong choice.";
}
return 0;
}
int volume(int a)
{
return a*a*a;
}
int volume(int a,int b,int c)
{
return a*b*c;
}
float volume(int a,int b)
{
return 3.142*a*a*b;
}