Function Overloading in C++

Video Tutorial
FREE
Function Overloading thumbnail
This video belongs to
C++ Course: Learn the Essentials
14 modules
Certificate
Topics Covered

Overview

Function overloading in C++ is a concept that allows two or more functions to have different logic but have a common function name. To overload functions, they must have a different set of parameters, i.e., either have parameters of different data types or a different number of parameters in the function definition.

Functions with different return types and identical parameters can not be overloaded. The determination to call a particular function is decided at the compile time. Function overloading not only improves code readability and reusability but also makes code faster and reduces memory space.

What Is Function Overloading In C++

Functions are a block of code written to perform specific actions. Function name helps the compiler to identify the operation the user wants to accomplish.

Still, we often want the same function to perform different actions based on inputs given to the function, just like a classroom can have more than one student with the same name. Still, they can have different heights, appearances, and personalities.

example of funtion overloading

One of the main features of C++ is function overloading. It is a concept where more than one function has different parameters but shares a common function name.

Using a unique set of arguments, we can redefine a function under an umbrella of a common function name, just like different varieties of apples have different sizes, textures, and colors. Still, all have the common name apple. In OOPs, this concept is also called the Function of Polymorphism.

As explained above, we can have two people with the same name but very different lives and personalities. Similarly, we often want our function to perform various operations but still have a common function name. Function overloading is a feature of object-oriented programming, which allows two or more functions to be created with the same name but with different arguments (different numbers of arguments or different data types of arguments).

For example:

Notice that the return types are not the same in the above four examples of the function area. Overloaded functions don't need different return types but must have different parameters.

For example:

Here, both functions have different return types, but because they have the same parameters, the C++ compiler will throw an error.

Function Overloading in C++ improves code readability and reusability, as programmers do not need to remember the various names of the functions.

Syntax

As explained from the definition of Function Overloading in C++, to overload two or more functions, they must have the same function name and parameters that are either a different number of parameters different data types of parameters or both.

Here, because three functions require different parameters to be passed during the function call, we can say the function function_name is overloaded.

Example Of C++ Function Overloading

To understand the concept of function overloading in C++, let us see some different examples.

Example 1 : Function to Calculate Different Areas

Suppose we want to create a function to calculate the area of different geometric figures. It makes more sense to have a function area() which calculates different actions on different types of inputs like :

  • When given a single value, calculate the area of a square.
  • For two input returns area assumes the figure is a rectangle.
  • When a floating-point number is passed to the function, it calculates and returns the area of a circle.

This can be done by overloading three functions with the same name and different arguments, as shown in the example below.

Output:

Here, the article shows the solution to the problem mentioned above. We have overloaded three functions with different arguments to calculate the area of a square, rectangle, or circle.

output of example 1

The compiler identifies which function to call based on the number of arguments and their data types passed to the function call.

Example 2: Overloading Using Different Types of Parameters

Functions can be overloaded when overloaded functions have parameters with different data types. Parameters with different data types help the compiler differentiate between several functions having a common name, and hence, they are one of the correct ways to overload functions in C++. Let us understand this with an example :

Output:

Here, based on the data type of parameters passed to the function during the function call, the compiler decides which function to call.

output of example 2 The first function is called when both arguments passed are integers, and the second function is called if the arguments passed to the function call are of type double.

Example 3 : Overloading using a Different Number of Parameters

Functions can also be overloaded if they have different numbers of arguments, as shown in the example :

``cpp #include using namespace std;

int sum(int a, int b) { // Function with name sum and, // returns the sum of two numbers. return a + b; }

int sum(int a, int b, int c) { // Function with name sum and, // returns the sum of three numbers. return a + b + c; }

int main() { // Calculating the sum of two numbers. int sum_1 = sum(5, 10); cout<<"5 + 10 = "<<sum_1<<endl;

// Calculating the sum of three numbers.
int sum_2 = sum(5, 10, 6);
cout<<"5 + 10 + 6 = "<<sum_2<<endl;

return 0;

}

**Output:**
```plaintext
5 + 10 = 15
5 + 10 + 6 = 21

Here, the sum() function is called twice with different parameters. The corresponding function sum () is called depending on the number of arguments passed to its function call. The corresponding function sum() is called.

output of example 3

Note: Here, both the overloaded functions sum() have the same return type, but this need not be the case for function overloading, and the overloaded functions can have the return value of different types.

How Does Function Overloading Work?

Function overloading must have:

  1. Same function name is used for more than one function definition.
  2. Overloaded functions must have different parameters. This difference can be created using a different number of function parameters or parameters of different data types in function definitions.

Following these two, the compiler can uniquely differentiate which function is to be called during the compile-time using some best match algorithm.

C++ is a statically typed programming language because variables can store the value of a particular data type (int, char, bool, etc.)

For example, a type int variable can only store integer values, or a char type variable can only store characters and not integers. Every time a function call is made, a type check is enforced in function arguments to ensure passed parameters and the data type of function argument matches its definition.

The decision of which function is to be called is made during the compile time. Hence, if two or more functions have the same name but different parameters, the compiler can differentiate these functions allowing us to use the concept of function overloading in the programs.

Rules Of Function Overloading in C++

For overloading function correctly, the parameters given to each function must be unique. This uniqueness in function arguments can be created using the three mentioned approaches.

rule of function overloading

1. Functions have Different Parameter Types

Every function can have arguments of different data types. For example :

2. Different Number of Parameters

Functions can have different number of parameters for the compiler to differentiate between them like

3. Functions Have Different Combinations of Arguments

Two or more functions can be overloaded if they have the same arguments but in different combinations, for example :

A program can have any number of overloaded functions until they follow any of the cases mentioned above or their combinations until their parameters are different. Note that functions with the same parameters but different return types are not correct overloadings. For example :

This will not work because the parameters of both functions have identical arguments (int a, int b).

Causes Of Function Overloading

When functions are not correctly overloaded, there can be a possibility of two or more overloaded functions satisfying the constraints passed in the function call; the compiler throws us an error because the call of the overloaded function is ambiguous.

Let us discuss some of these common compilation errors that occur because of incorrect overloading of the functions.

1. Type Conversion

In C++, when the data type of a floating number is not defined, they are treated as type double instead of type float. Whenever floating values are directly passed in a function call, we should ensure that the data type of variables that take the value in function arguments are of type double, or else the compiler throws an error, as shown in the example below :

Output:

Ideally, abs(-5) should call the second function and abs(3.4) should trigger the first function, and we should get the expected output from the code; instead, the code generates an error call of overloaded abs(double) is ambiguous.

We get an error because, in C++, floating-point constants are treated as type double and not float. Hence, replacing parameter type with double program will execute correctly. We call this error type conversion error from float to double.

Click here, to learn more about Type Conversion in C++.

2. Function with Default Arguments

C++ allows function arguments to hold a default value, and the argument is assigned this value when no value is passed to the function argument in the function call. Often, when functions with a default value for their arguments are overloaded, it can lead to compilation error, and we used to pay extra attention to avoid such cases.

Let us understand this case with an example :

Output:

This program throws us an error call of overloaded area(int) is ambiguous because the function area(length, breadth) can be called in two ways :

  1. Passing two arguments to the function call area(10,12).
  2. Passing one argument to the function call area(10) and because the function has a default value for the second parameter (1), the value of breadth will be set to its default value.

function with default arguments

When we create a function called area(10), we fulfill conditions for either of the two functions, which causes the ambiguity error because the compiler can not decide which function is called.

3. Function with Pass by Reference

There are two ways to create a function call: by value or reference. When parameters to a function are passed by their reference, such calls are called call by reference. When we try to overload functions that have parameters passed by reference, we should be extra careful because overloaded functions call is often ambiguous. The compiler, in such cases, fails to differentiate between them and hence throws an error. One such scenario is shown in the example below :

Output:

Here, the parameter of the first function increment() is passed by value, and on the other hand, the second function has an integer argument passed by reference. Syntactic function call for both functions increment(int) and increment(int&) are the same, and this is the reason the compiler throws an error call of the overloaded increment(int&) is ambiguous.

Benefits Of Function Overloading in C++

  1. Function overloading in C++ improve code readability and reusability and makes it easier to understand.
  2. Function overloading in C++ allows for the development of more than one function with the same name, eliminating the use of different function names.
  3. Use of function overloading in C++ improves consistency, and also maintaining a large code becomes easy and brings flexibility to the code.

Conclusion

  • Function Overloading in C++ is a concept that allows two or more functions to have different tasks but a common function name.
  • Functions can be overloaded in C++ if they have different parameters, either by having parameters with varying data types or having a different number of parameters in the function definition.
  • Difference in function parameters can be made using
    • Parameters with different data types.
    • Different number of parameters in the function definition.
    • Different combinations of parameters in the function definition.
  • Overloading is done during compile time, and the compiler knows which function is getting called before execution.
  • Function overloading in C++ increases code readability and reusability.

Read Also: