Function Overloading and how it is resolved in C++

 What is Function Overloading?

  • Function overloading is a way to achieve polymorphism.
  • There is function overloading when more than one functions with the same name but different parameter list exist in the program.
#include<iostream.h>
using namespace std;
int area(int, int);
float area(int);

void main()
 {
  int r;
  cin>>r;
  float A = area(r);
  cout<<"Area of Circle is: "<<A;
  
  int l,b,a;
  cin>>l>>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);
}

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 while 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?

  • First, C++ compiler tries to find an exact match by seeing the function call. This is the case where the actual argument exactly matches the parameter type of one of the overloaded function.
  • If no exact match is found , C++ compiler tries to find a match through promotion.
  • char, unsigned char and short is promoted to  an int.
  • float is promoted to double.
  • If no promotion is found, C++ compiler tries to find a match through standard conversion.
<< Previous                                                                                      Next >>
Previous
Next Post »

Comment Below: ConversionConversion EmoticonEmoticon