If more than one functions having same name but differing in terms of number and types of argument it takes is used in a class, it is known as function overloading. It is an example of compile time polymorphism (static/early binding). The compiler determines which function is called during compile time based on the number and types of argument sent.
Functions which have same name but different arguments(either type of argument or number of argument/s or both) are known as overloaded functions in C++ Programming. The compiler determines which function to invoke during compile time based on the number and types of argument sent. Function overloading is an example of compile time polymorphism.
/* Examples of Function overloading*/ int addNumber() { } int addNumber(int a) { } int addNumber(int a, float b) { } int addNumber(double a, int b) { }
The return type of overloaded functions can be same or different but argument/s is always different.
C++ Function Overloading Example
C++ program to find the area of various geometrical shapes by function overloading.
#include <iostream> #include <conio.h> #include <math.h> #define pie 3.14 using namespace std; class shape { public: float area(float a) { return (pie*a*a); } float area(float a, float b) { return (a*b); } float area(float a, float b, float c) { float s, temp; s = (a+b+c)/2; temp = s*(s-a)*(s-b)*(s-c); temp = pow(temp,0.5); return temp; } }; int main() { float radius,length,breadth,side[3]; shape circle, rectangle, triangle; cout<<"Enter radius of circle: "; cin>>radius; cout<<"Area of circle="<<circle.area(radius) << " sq. unit" << endl<< endl; cout<<"Enter length and breadth of rectangle: "; cin>>length>>breadth; cout<<"Area of rectangle=" << rectangle.area(length, breadth) << " sq. unit" << endl << endl; cout<<"Enter three sides of a triangle: "; cin>>side[0]>>side[1]>>side[2]; cout<<"Area of rectangle="<<triangle.area(side[0],side[1],side[2])<<" sq. unit"<<endl; getch(); return 0; }
Output
Enter radius of circle: 4 Area of circle=50.24 sq. unit Enter length and breadth of rectangle: 9 4 Area of rectangle=36 sq. unit Enter three sides of a triangle: 4 6 7 Area of rectangle=11.9765 sq. unit
In the above example, area() function is overloaded three times. If 1 argument is passed, the area() function with one argument is called and returns area of circle. Similarly, if 2 and 3 arguments are passed, the area() function with two arguments and three arguments is called respectively.
If two or more functions with same name and same and types of argument is created then error will occur as the compiler can’t separate these functions.