Function Overloading and how it is resolved in C++

 What is Function Overloading?

1. Function overloading is a way to achieve polymorphism.

2. There is function overloading when more than one functions with the same name but different parameter list exist in the program.

Example: Function Overloading in C++
#include<iostream>
using namespace std;

int area(int, int);
float area(int);

int main()
{
  int r;
  
  cout << "Enter Radius of Circle: " << endl;
  cin >> r;
  
  float A = area(r);
  cout << "Area of Circle is: " << A << endl;
  
  int l, b, a;
  
  cout << "Enter Length of Rectangle: " << endl;
  cin >> l;
  
  cout << "Enter Breadth of Rectangle: " << endl;
  cin >> b;
  
  a = area(l, b);
  cout << "Area of Rectangle is: " << a;
}

float area(int R)
{
  return (3.14 * R * R);
}

int area(int L, int B)
{
  return (L*B);
}
Output:
Enter Radius of Circle: 
3.5
Area of Circle is: 28.26
Enter Length of Rectangle:
8
Enter Breadth of Rectangle: 
6
Area of Rectangle is: 48

Early binding vs Late binding

It is the work of compiler to bind the function's correct definition by seeing its call. 

This binding can be done at compile time or run time. They are called early binding and late binding. 

The binding (also called mapping or connecting)  done by the compiler at compile time is called early binding.

Late binding (or dynamic binding) is the binding done by the compiler at the run time. 

Virtual keyword is used to tell compiler that late binding should be done.

How function overloading is resolved?

1. First, C++ compiler tries to find an exact match by seeing the function call. 

2. This is the case where the actual argument exactly matches the parameter type of one of the overloaded function.

3. If no exact match is found , C++ compiler tries to find a match through promotion.

4. char, unsigned char and short is promoted to  an int.

5. float is promoted to double.

6. If no promotion is found, C++ compiler tries to find a match through standard conversion.

Previous
Next Post »