Dremendo Tag Line

Function Overloading in C++ Programming

Function in C++

In this lesson, we will understand what is function overloading in C++ programming and how to create them along with some examples.

What is Function Overloading in C++?

Function Overloading in C++ is a process in which we declare more than one function having the same name but with different numbers of arguments. By overloading a function, we can perform more than one task using the same name.

Suppose we declare a function called sum that takes two arguments for addition and another function with the same name, sum that takes three arguments for addition. In this case, we have overloaded the function sum.

Let's see an example of how we can overload a function in C++.

video-poster

Function Overloading Example 1

#include <iostream>
#include <conio.h>

using namespace std;

int max(int a, int b)
{
    int m=0;
    if(a>b)
    {
        m=a;
    }
    else if(b>a)
    {
        m=b;
    }
    return m;
}

// Overloading the max function to find maximum among 3 integer numbers
int max(int a, int b, int c)
{
    int m=0;
    if(a>b && a>c)
    {
        m=a;
    }
    else if(b>a && b>c)
    {
        m=b;
    }
    else if(c>a && c>b)
    {
        m=c;
    }
    return m;
}

int main()
{
    int x,y,z;
    cout<<"Enter 2 integer numbers"<<endl;
    cin>>x>>y;
    cout<<"Maximum number = "<<max(x,y)<<endl;;
    cout<<"Enter 3 integer numbers"<<endl;
    cin>>x>>y>>z;
    cout<<"Maximum number = "<<max(x,y,z);
    return 0;
}

Output

Enter 2 integer numbers
15
36
Maximum number = 36
Enter 3 integer numbers
84
21
79
Maximum number = 84

In the above example, we have created two functions having the same name but with a different number of arguments. The first one will receive two integer numbers and return the maximum among the two numbers. The second function will receive three integer numbers and return the maximum among the three numbers.

It's not compulsory to use the same arguments while we overload a function. We can use different types of arguments during function overloading as per our requirements. See the example given below.

Function Overloading Example 2

#include <iostream>
#include <conio.h>

using namespace std;

float sum(int a, float b)
{
    float s=0;
    s=a+b;
    return s;
}

// Overloading the sum function to find the sum of three different types of numbers
double sum(int a, float b, double c)
{
    double s=0;
    s=a+b+c;
    return s;
}

int main()
{
    int x;
    float y;
    double z;
    cout<<"Enter one integer and one decimal numbers"<<endl;
    cin>>x>>y;
    cout<<"Sum = "<<sum(x,y)<<endl;;
    cout<<"Enter one integer and two decimal numbers"<<endl;
    cin>>x>>y>>z;
    cout<<"Sum = "<<sum(x,y,z);
    return 0;
}

Output

Enter one integer and one decimal numbers
12
14.24
Sum = 26.24
Enter one integer and two decimal numbers
25
15.364
42.2562
Sum = 82.6202