You are here

C++ function overloading programs

Function overloading in C++: C++ program for function overloading. Function overloading means two or more functions can have the same name but either the number of arguments or the data type of arguments has to be different. Return type has no role because function will return a value when it is called and at compile time compiler will not be able to determine which function to call. In the first example in our code we make two functions one for adding two integers and other for adding two floats but they have same name and in the second program we make two functions with identical names but pass them different number of arguments. Function overloading is also known as compile time polymorphism.

C++ programming code

#include <iostream>
 
using namespace std;
 
/* Function arguments are of different data type */
 
long add(long, long);
float add(float, float);
 
int main()
{
   long a, b, x;
   float c, d, y;
 
   cout << "Enter two integers\n";
   cin >> a >> b;
 
   x = add(a, b);
 
   cout << "Sum of integers: " << x << endl;
 
   cout << "Enter two floating point numbers\n";
   cin >> c >> d;
 
   y = add(c, d);
 
   cout << "Sum of floats: " << y << endl;
 
   return 0;
}
 
long add(long x, long y)
{
   long sum;
 
   sum = x + y;
 
   return sum;
}
 
float add(float x, float y)
{
   float sum;
 
   sum = x + y;
 
   return sum;
}

In the above program, we have created two functions "add" for two different data types you can create more than two functions with same name according to requirement but making sure that compiler will be able to determine which one to call. For example you can create add function for integers, doubles and other data types in above program. In these functions you can see the code of functions is same except data type, C++ provides a solution to this problem we can create a single function for different data types which reduces code size which is via templates.

C++ programming code for function overloading

#include <iostream>
 
using namespace std;
 
/* Number of arguments are different */
 
void display(char []);  // print the string passed as argument
void display(char [], char []);
 
int main()
{
   char first[] = "C programming";
   char second[] = "C++ programming";
 
   display(first);
   display(first, second);
 
   return 0;
}
 
void display(char s[])
{
   cout << s << endl;
}
 
void display(char s[], char t[])
{
   cout << s << endl << t << endl;
}

Output of program:

C programming
C programming
C++ programming