Function Overloading in C++

In this tutorial, you will learn all about Function Overloading in the C++ programming language. C++ programming has awesome features and one of the most powerful features is function overloading. It means a code holding more than one function with the same signature but with complex argument lists.

The argument list indicates the flow of the arguments and data types of arguments. Function overloading determines similar operations. It improves the readability of the code. Redefined the function because there is no point in creating two separate functions for performing the same work again and again.

Syntax

void test(int a, int b);
void test(float a, float b);

Both functions are the same but arguments are different. So, In case you want to perform subtraction on different data types using the same function then use the function overloading feature.

Here is the C++ code to display Function overloading in C++ programming:
Function overloading Example

#include <iostream>
using namespace std;
class A
{   int b;
public:
A(){}
A(int c)
{
b=c;
}
void operator+(A);
void display();
};
void A :: operator+(A a)
{
int n = b+a.b;
cout<<"The addition of two objects is= : "<<n;
}
int main()
{
A a1(786);
A a2(786);
a1+a2;
return 0;
}
Output
The addition of two objects is= : 1572

In the above example, we made a class A and built an integer variable b, and then held two constructors. So, that we don’t have to create objects for calling the function as constructor automatically. Therefore, Initializes a newly created class object just after a memory is allocated. Two functions are built operator and display to show the addition of two objects using function overloading concepts.

Advantages of Function overloading

The central advantage of function overloading is to increase code readability and allow code reusability. In the above example, We have seen how we were able to have more than one function for the same task(addition) with different parameters, this allowed us to add two integer numbers as well as three integer numbers if we wanted we could have some more functions with the same name and four or five arguments. Imagine if we didn’t have function overloading, we either have the limitation to add only two integers or we had to write different name functions for the same task addition, this would reduce the code readability and reusability.

Conclusion

In Conclusion, the function overloading feature in C++ can be worked in various ways to improve code readability. It helps in saving memory space as well as compilation time while programming with the C++ language. Learn Function Overriding.

Leave a Reply

Your email address will not be published. Required fields are marked *