OOAD Princhiples Q/A #6


Question:What do you mean by overloading of a function? When do you use this concept? Give an example of function overloading?

Answer:

Function overloading

Function overloading is a technique where several function declarations are specified with a same name that can perform similar tasks, but on different data types. Such functions are considered to be overloaded. C++ allows functions to have the same name. These functions can be distinguished by their number and type of arguments.

Example

int add (int a, int b);
int add (int a, int b, int c);
float add (float a, float b);

The function add(int a, int b) takes two integer inputs is different from the function add(int a, int b,int c) which takes three integer inputs and add(float a, float b) which takes two float inputs. When an overloaded function is called , the C++ compiler selects the proper function by examining the number, types and order of the arguments in the function call. Thus an overloaded function performs different activities depending upon the kind of data sent to it. Function overloading not only implements polymorphism but also reduces number of comparisons in a program and thereby make the program run faster.

Program to explain function overloading

#include<iostream>
#include<math>

using namespace std;

float area (float a, float b, float c)
{
   float s, ar;
   s = (a+b+c)/2 ;
   ar = sqrt (s*(s-a)* (s-b)*(s-c));
   return (ar);
}
float area (float a, float b)
{
   return (a*b);
}
float area (float a )
{
   return (3.14*a*a);
}
int main ( )
{
   int choice ;
   float s1,s2,s3, ar;

   do
   {
      cout <<" Area\n";
      cout <<"1.Rectangle\n";
      cout <<"2.triangle\n";
      cout <<"3.circle\n";
      cout <<"4.exit\n";
      cout <<"enter your choice:";
      cin>> choice ;
      switch (choice)
      {
         case 1: cout <<"enter length and breadth\n";
            cin >>s1>>s2;
            ar =area (s1,s2);
            break;
         case 2:  cout <<"enter three sides\n";
            cin >>s1>>s2>>s3;
            ar =area (s1,s2,s3);
            break;
         case 3: cout <<"enter radius\n";
            cin >>s1;
            ar =area (s1);
            break;
         case 4: break;
         default :cout <<"wrong choice";
      }
      cout<<"the area is "<<ar <<endl:
   } while (choice!=4);
   return 1;
}

Output

 
Area 
1. Rectangle
2. triangle
3. circle
4. Exit 
Enter your choice :1
Enter length and breadth
10 20
The area  is 200
Area 
1. Rectangle
2. triangle
3. circle
4. Exit 
Enter your choice :2
Enter three sides
3 4 5
The area is 6
Area 
1. Rectangle
2. triangle
3. circle
4. Exit 
Enter your choice :3
Enter radius 
10
The area is 314
Area 
1. Rectangle
2. triangle
3. circle
4. Exit 
Enter your choice : 4
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements