Overloading means use of same thing for different purposes. Using function overloading we can perform different tasks with the same function name depending on the argument list. Function overloading is a concept of polymorphism.
Rules while creating function overloading:
Example 1: Find sum of 2 numbers and 3 numbers using function overloading.
#include<iostream.h> using namespace std; //function declaration int sum (int , int); int sum (int , int, int ); int main() { int a, b, c, sum1, sum2; cout<<"Enter 2 numbers: "; cin>>a; cin>>b; sum1 = sum(a, b); // function call cout<<"Sum of 2 numbers is: "<<sum1; cout<<"Enter 3 numbers: "; cin>>a; cin>>b; cin>>c sum2 = sum(a, b, c); //! function call cout<<"Sum of 3 numbers is: "<<sum2; return 0; } // function definition int sum (int a, int b) { int c; c = a+b; return c; } int sum (int a, int b , int c) { int d; d = a+b+c; return d; }
#include<iostream.h> #include<conio.h> float area (float r); // function declaration for area of circle int area (int l, int b); // function declaration for area of rectangle void main() { clrscr(); float r, a2; int l, b, a1; cout<<"Enter radius of circle: "; cin>>r; cout<<"Enter Length of rectangle: "; cin>>l; cout<<"Enter Breadth of rectangle: "; cin>>b; a1 = area(l,b); //function calling (rectangle) a2 = area(r); //function calling (circle) cout<<"Area of Circle = "<< a2 << endl; cout<<"Area of Rectangle = "<< a1; getch(); } float area (float r) { float a; a = 3.14 * r * r; return a; } int area (int l, int b) { int a; a = l * b; return a; } Output: Enter radius of circle: 5 Enter Length of rectangle: 10 Enter Breadth of rectangle: 20 Area of Circle = 78.5 Area of Rectangle = 200
#include <iostream> using namespace std; int area (int l, int b); float area (float r); int area (int s) { int a; a = s*s; return a; } int main() { int n, l, b, a, s; float r, a2; cout << "Enter number to find area\n"; cout << "1 - Rectangle"<<endl; cout << "2 - Circle"<<endl; cout << "3 - Square"<<endl; cin>>n; switch(n) { case 1: cout<<"Enter length, breadth"; cin>>l>>b; a=area(l,b); cout<<"Area of Rectangle = " << a; break; case 2: cout<<"Enter Radius"; cin>>r; a2=area(r); cout<<"Area of Circle = " << a2; break; case 3: cout<<"Enter side"; cin>>s; a=area(s); cout<<"Area of Square = " << a; break; } return 0; } int area (int l, int b) { int a; a = l * b; return a; } float area (float r) { float a2; a2 = 3.14 * r*r; return a2; }