In C++ language, we can use create a more than one function with same name but each function must have different parameter list.
Such functions are called overloaded function and this process is known as function overloading.
Function overloading is an example of polymorphism.
Polymorphism means one function having many forms .
Example of function overloading:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #include <iostream> using namespace std; void show(); void show(int); void show(char); int main() { show(); show(10); show('a'); } void show() // overloaded function { cout << "inside show"<<endl; } void show(int a) // overloaded function { cout << "a = " << a<<endl; } void show(char c) // overloaded function { cout << "character = " << c<<endl; } |
Output
1 2 3 | inside show a = 10 character = a |
Description: In the above program, we have created a three function with same name “show” but each show() function have a different parameter list
Que. Write a C++ program to calculate the area of rectangle , triangle and circle using function overloading .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | #include <iostream> using namespace std; void area(double); void area(int, int); void area(double, double); int main() { area(5.5); area(10, 20); area(10.1, 11.2); } void area(double r) // overloaded function { cout << "\n Area of circle =" << (3.14 * r * r); } void area(int l, int b) // overloaded function { cout << "\n Area of rectangle =" << (l * b); } void area(double b, double h) // overloaded function { cout << "\n Area of triangle =" << ((0.5) * b * h); } |
Output
1 2 3 | Area of circle =94.985 Area of rectangle =200 Area of triangle =56.56 |
Function Overloading in Classes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #include <iostream> using namespace std; class example { public: void show() // overloaded function { cout << " Inside show"; } void show(int a) // overloaded function { cout << "\n a=" << a; } void show(char c) // overloaded function { cout << "\n character =" << c; } }; int main() { example obj; obj.show(); obj.show(10); obj.show('z'); } |
Output
1 2 3 | Inside show a=10 character =z |