Write a C++ program to calculate the area of circle, rectangle and square using function overloading.

As given in the program definition, we have to find area of circle, rectangle and square using function overloading.

What is Function Overloading? πŸ€”

C++ allows us to have multiple definitions of same name function in same scope but their signature must be different, is known as Function Overloading.

Tutorial πŸ“Ί

Watch the tutorial to understand how to solve this problem. πŸ˜‡

Steps πŸͺœ

To Find Area using Function Overloading

  1. Declare and define 3 definition of area() function to calculate the area of circle, rectangle and square.
  2. In Circle’s area() function, display a message to ask user to input radius of circle. Next, display the area of circle, after accepting the radius of circle.
  3. Square’s area() function should take an argument of floating point type and simply displays the area of square based on the accepted argument.
  4. Rectangle’s area() function should take two arguments of floating point type and display the area of rectangle based on the accepted arguments.
  5. In main() function, simply call the area() functions to find the area of circle, rectangle and square.

Code πŸ’»

#include <iostream.h>
#include <conio.h>

// Area of Circle
void area()
{
  float r = 0;
  cout << "Please enter the radius: ";
  cin >> r;
  cout << "\nArea of Circle: " << 3.14 * r * r << endl;
}

// Area of Square
void area(float s)
{
  cout << "\nArea of Square: " << s * s << endl;
}

// Area of Rectangle
void area(float l, float w)
{
  cout << "\nArea of Rectangle: " << l * w << endl;
}

/* 
  NOTE: Some compilers may not support clrscr() and getch() functions. 
  In that case, comment them. 
*/

void main()
{
  clrscr();
  area(); // Circle
  area(2.0f); // Square
  area(2.0f, 3.0f); // Rectangle
  getch();
}

Output 😍

In above code, the user will be asked to enter the radius of circle. Let’s assume, the user enters 3 and the output will be displayed as:

Please enter the radius: 3

Area of Circle: 28.26

Area of Square: 4

Area of Rectangle: 6

This is how we calculate the area of circle, rectangle and square using function overloading in C++.
For more C++ Programs, click here.