WAP using function overloading to find the area of rectangle triangle , Circle and square
Objective
Write a C++ program to find the area of different shapes using Function Overloading.
Algorithm / Approach
- Create a
class Test. - Define multiple functions all named exactly
area, but with different parameters (e.g.,area(int, int)for rectangle,area(double)for circle, etc.). - In
main(), read dimensions for all shapes. - Call the
t.area()function repeatedly, passing the different dimensions as arguments.
main.cpp
#include<iostream>
#include<math.h>
using namespace std;
class Test {
public :
void area(int l, int b){
int a = l*b;
cout<<"Area of Rectangle = "<< a;
cout<< endl;
}
void area(double r) {
double a = 3.14*r*r;
cout<<"Area of Circle = "<< a;
cout<< endl;
}
void area(int a, int b, int c ){
double s = (a+b+c)/2.0;
double ar;
ar=sqrt(s*(s-a)*(s-b)*(s-c));
cout<<"Area of Triangle = "<< ar;
cout<< endl;
}
void area(int a){
int ar = a*a;
cout<<"Area of Square = "<< ar;
cout<< endl;
}
};
int main() {
int l,b,s,s1,s2,s3;
double r;
cout<<"Enter Length, Breadth ";
cin>>l>>b;
cout<<"Enter Radius of circle ";
cin>>r;
cout<<"Enter Side of square ";
cin>>s;
cout<<"Enter Sides of triangle ";
cin>>s1>>s2>>s3;
Test t;
t.area(l,b);
t.area(r);
t.area(s);
t.area(s1,s2,s3);
return 0;
}
Expected Output
Enter Length, Breadth 4 3 Enter Radius of circle 7 Enter Side of square 5 Enter Sides of triangle 3 4 5 Area of Rectangle = 12 Area of Circle = 153.86 Area of Square = 25 Area of Triangle = 6
Explanation of the Program
- Function Overloading allows you to have multiple functions with the exact same name, as long as they have different parameters (different number of arguments or different data types).
- When you call
t.area(4, 3), C++ automatically looks for the version ofareathat accepts exactly two integers, and runs that specific block of code.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)