C++ Program to illustrate function overloading [DEVCPP/GCC]


FUNCTION OVERLOADING

C++ allows specification of more than one function under the same name in the same scope. These functions must have different signatures and are called overloaded functions. Overloading of functions allow programmer to define different semantics for a function, depending upon number and type of arguments.

For instance, in order to find maximum number, the function max() can be overloaded as:

int max (int num1, int num2);
int max (int num1, int num2, int num3);

Although functions can be distinguished on the basis of return type, they cannot be overloaded on this basis. 

PROGRAM

/* Program to calculate area of square, rectangle and circle using overloaded function area */

#include <iostream>

using namespace std;

float area( int length, int breadth )
{
        return (length * breadth);
}

float area( int side )
{
        return (side * side);
}

float area( float radius )
{
        return (3.14 * radius * radius);
}

int main()
{
        char ch='y';
        int s,c,l,b;
        float r;

        do
        {
              cout<<"\n\n\t***AREA CALCULATOR***";
              cout<<"\n 1. SQUARE";
              cout<<"\n 2. RECTANGLE";
              cout<<"\n 3. CIRCLE";
              cout<<"\n 4. EXIT";
              cout<<"\nENTER YOUR CHOICE(1-4): ";
              cin>>c;

              switch(c)
              {
                      case 1:
                      {
                              cout<<"\nENTER SIDE: ";
                              cin>>s;

                              cout<<"AREA OF SQUARE: "<<area(s);
                              break;
                    }

                    case 2:
                      {
                              cout<<"\nENTER LENGTH: ";
                              cin>>l;
                              cout<<"ENTER BREADTH: ";
                              cin>>b;

                              cout<<"AREA OF RECTANGLE: "<<area(l,b);
                              break;
                      }

                      case 3:
                      {
                               cout<<"\nENTER RADIUS: ";
                               cin>>r;

                               cout<<"AREA OF CIRCLE: "<<area(r);
                               break;
                       }

                       case 4:
                       {
                                exit(0);
                        }

                        default:
                        {
                                 cout<<"YOU ENTERED WRONG CHOICE!";
                        }
             }

             cout<<"\n\nDO YOU WANT TO CONTINUE(Y/N): ";
             cin>>ch;

         }while(ch=='Y' || ch=='y');
}

OUTPUT


C++ Program to illustrate function overloading


Share this

Related Posts

FIND US ON FACEBOOK!