Introduction

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.

For example,

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++.

Outputs:

For Square
Triangle
Rectangle

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.

Conclusion

So in this tutorial, we learned the concept of function overloading in C++. For any further questions, feel free to use the comments below.

References

By admin

Leave a Reply

%d bloggers like this: