Saturday, 25 May 2013

C++ Tutorial 1: Function Overloading

In general, overloading refers to using same things for different purposes. In case of functions, when the same function name is used for different tasks, it is called as function overloading. Say if we want to calculate area of certain shapes, it would be easier for us to call the function with the same name as "area()" for all the shapes than remembering individual names. So, function overloading is one of the important features in Object Oriented Programming. In C++, when an overloaded function is called, the function with matching arguments and return type is called and executed. See the example below for better understanding of this concept.

/*Write a program using function overloading that calculates the volume of a cube, a cylinder and a rectangular box. Use the overloaded functions with suitable arguments to achieve this.*/
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
#define PI 3.14159

float volume(int side){     //for volume of a cube
return (side*side*side);
}
float volume(int radius, int height){     //for volume of a cylinder
return (PI*radius*radius*height);
}
float volume(int length, int width, int height){     //for volume of a rectangular box
return (length*width*height);
}

void main(){
clrscr();
   int side, r, ht, l, w, h, ch;
   float vol;
   cout<<"Select the shape to find volume: ";
   cout<<endl<<"1.Cube"<<endl<<"2.Cylinder"<<endl<<"3.Rectangular Box"<<endl<<":";
   cin>>ch;

    switch(ch){
      case 1:
          cout<<endl<<"Enter the length of a side: ";
          cin>>side;
          vol = volume(side);
          break;
case 2:
          cout<<endl<<"Enter the radius: ";
          cin>>r;
            cout<<endl<<"Enter the height: ";
            cin>>ht;
          vol = volume(r,ht);
            break;
         case 3:
          cout<<endl<<"Enter the length: ";
          cin>>l;
            cout<<endl<<"Enter the width: ";
            cin>>w;
            cout<<endl<<"Enter the height: ";
            cin>>h;
          vol = volume(l,w,h);
            break;
         default:
          cout<<endl<<"Invalid Choice!!";
            goto end;
      }
cout<<endl<<"Volume = "<<vol<<" cubic units";
end:
   getch();
}

©Dixit Bhatta 2013

No comments:

Post a Comment

Was this post helpful? Ask any questions you have, I will try to answer them for you.