Today in this tutorial, we are going to understand the concept of Function Overloading in C++.
So now let’s get started.
What is Function Overloading?
The C++ programming language provides its users with a very useful feature that is function overloading. It allows the users to use the same name for two or more functions with a different number or types of arguments they accept.
int demo(int, int);
Here we have used the same function name
demo for declaration of three different functions. Notice all of them take different number or type of arguments. So, all these functions can be used in a single program and the function call would be solely dependent on the type and number of arguments passed.
For instance, the below function (though having different return types) would raise an error if used with the above functions.
This is because it takes the same type and number of argument as of the first function declared earlier.
Example – Calculating perimeter using Function Overloading in C++
Now let us look at an easy example where we try to calculate the perimeter of a square/triangle/rectangle on the basis of the user’s choice by implementing the function overloading concept in C++.
using namespace std;
float peri(float x)
float peri(float a, float b, float c)
float peri(float l, float b)
float x, y, z;
cout<<"::: Menu for calculating perimeter :::"<<endl;
cout<<"Enter your choice(1/2/3) : ";
case 1: cout<<"nnEnter edge for the Square: ";
cout<<"nPerimeter = "<<peri(x)<<" units";
case 2: cout<<"nnEnter 1st side length: ";
cout<<"nEnter 2nd side length: ";
cout<<"nEnter 3rd side length: ";
cout<<"nPerimeter = "<<peri(x,y,z)<<" units";
case 3: cout<<"nnEnter length for the Rectangle: ";
cout<<"nEnter breadth for the Rectangle: ";
cout<<"nPerimeter = "<<peri(x,y)<<" units";
default: cout<<"Wrong Choice!";
Here, we use a switch-case to calculate the perimeter of any one of the squares, triangles, or rectangles.
ch is the user’s choice which determines the shape for which the data input is to be taken.
After taking the user’s choice inside the
switch-case we take the data for the different shapes and pass them to the
peri() function in order to print the corresponding perimeter.
In this case, the function call for
peri() totally depends on the number of arguments that are passed to it. Hence on a single parameter, the compiler automatically calls the first function and returns the perimeter for a square.
And accordingly, for two and three parameters, the corresponding functions to calculate the perimeter for a rectangle and a triangle are called respectively.
So in this tutorial, we learned the concept of function overloading in C++. For any further questions, feel free to use the comments below.