Website For Developers

Function Overloading in C++




Example of function overloading:

//three versions of function in line
#include<iostream>
#include<conio.h>
using namespace std;
void line() {
  int i;
  for(i=1; i<=10; i++)
  cout<<"*";
  cout<<endl;
}
void line(int n) {
  int i;
  for(i=1; i<=n; i++)
  cout<<"*";
  cout<<endl;
}
void line(int n, char c) {
  int i;
  for(i=1; i<=n; i++)
  cout<<c;
  cout<<endl;
}
int main() {
  int n = 5;
  char c = 'a';
  line();
  line(n);
  line(n, c);
  getch();
  return 0;
}

Output

**********
*****
aaaaa



2nd Example of function overloading:

#include<iostream>
#include<conio.h>
using namespace std;
// Sum of integer values
int sumFactory(int a, int b) {
  int c = a+b;
  return c;
}
// Sum of float values
float sumFactory(float x, float y) {
  float c = x+y;
  return c;
}
int main() {
  int a = 10, b = 5;
  float x = 2.2, y = 9.1;
  int intSum = sumFactory(a,b);
  float floatSum = sumFactory(x,y);
  cout<<"Total of Integer values: "<<intSum;
  cout<<endl<<"Total of Float values: "<<floatSum;
  getch();
  return 0;
}

Output

Total of Integer values: 15
Total of Float values: 11.3