What is Function Overloading with example?

All QuestionsCategory: Cpp LanguageWhat is Function Overloading with example?
Anonymous asked 3 years ago
1 Answers
Anonymous answered 3 years ago

In C++, two or more functions can have the same name with different prototypes, which is known as overloading. Function overloading is the basis for compile-time polymorphism. Here functions undergo static/early binding.
 
Rules for resolving function calls
 

  • Identify all functions with the same name as a function call, consider them as candidate functions
  • If no candidate function (no match by function name), the call will be a failure (syntax error)
  • Among one more candidate functions
  • Identify suitable definition with an exact match, if so call will be successful|
  • If no exact match, try for near matches with some implicit conversions
    • If only one near match is found, the call will be successful
    • If no near match at all, the call will be a failure (syntax error)
    • If multiple near matches are possible, the call will be ambiguous (syntax error)

 
Example Code
 

int sum(int, int);
int sum(int, int, int);
float sum(float, float);    //function overloading

int main() {

int a = 10, b = 20, c = 30;
float x = 2.3f, y = 5.6f, z = 8.2f;
double p = 2.3, q = 5.6, r = 8.2;
char c1 = 'A', c2 = 32;

sum(a, b);
sum(x, y);
sum(a, b, c);

sum(x, y, z);
sum(p, q, r);
sum(c1, c2);

// sum(p,q);
// sum(a,x);
// sum(x,b);
// sum(&a,&b);
// sum(a,b,x,y);

return 0;

}

int sum(int x, int y) { return x + y; }

int sum(int x, int y, int z) { return x + y + z; }

float sum(float x, float y) { return x + y; }