In C++, function overloading is a capability of object-oriented programming that allows different functions to share a common name while having unique parameter lists (differing in type, quantity, or both). This functionality enhances code clarity, reusability, and efficiency by empowering a function to process various input types while upholding a uniform interface. The versatility in function design is enabled as the compiler selects the appropriate function to execute based on the provided inputs. This feature can be viewed as a demonstration of polymorphism within C++.
Syntax:
It has the following syntax:
return_type function_name(parameter1);
return_type function_name(parameter2);
In this code structure, we've included two function definitions with identical names but distinct parameters:
Simple Function Overloading Example:
Let's consider a program to demonstrate function overloading in C++.
Example
#include<iostream>
using namespace std; //using standard namespace
int sum(int a, int b) //Add two numbers
{
return a + b;
}
int sum(int a, int b, double c) //Add three double numbers
{
return a + b + c;
}
float sum(float a, float b) // Add two floating-point numbers
{
return a + b;
}
int main() {
cout<<sum(15, 20)<<endl;
cout<<sum(5, 7, 9.4)<<endl;
cout<<sum(5.7f, 8.4f)<<endl;
return 0;
}
Output:
35
21
14.1
Explanation:
In this instance, we've selected three function declarations featuring identical names yet varying parameters.
How does Function Overloading Work in C++?
There are several steps that helps us to understand how function overloading works in C++.
- Exact Match: First, the compiler looks for a function with the same name and an exact parameter match.
- Implicit Conversion: If no exact match is found: The char, unsigned char, and short are converted to int. The float is converted to double.
- Standard Conversion: If there is no match, C++ uses implicit type conversions to relsove it.
- Compilation Error: If no suitable function is discovered after conversion attempts, a compilation error will result.
- The char, unsigned char, and short are converted to int.
- The float is converted to double.
Types of Function Overloading in C++:
In C++ , function overloading depends on the function name and the number or types of parameters. The return type alone cannot differentiate overloaded functions. If two functions have identical parameter lists but different return types, a compilation error occurs due to ambiguity. There are three types of function overloading, and they are:
- Function Overloading Based on Number of Parameters.
- Function Overloading Based on Different Parameter Types.
- Function Overloading Based on Different Parameter Orders.
1. Function Overloading Based on Number of Parameters:
Function overloading enables the creation of multiple functions sharing identical names but differing parameters. This allows the compiler to select the appropriate function based on the number of arguments supplied during function invocations. This practice enhances the clarity, adaptability, and ease of maintenance of the codebase.
Syntax:
It has the following syntax.
void displayData(int value); // Function with 1 parameter.
void displayData(int value, double rate); // Overloaded function with 2 parameters.
void displayData(int value, double rate, string text); // Overloaded function with 3 parametes.
C++ Function Overloading Based on Number of Parameters Example:
A C++ code example showcasing Function Overloading Depending on the Quantity of Arguments.
Example
#include <iostream>
#include <string>
using namespace std; //using standard namespace
//Function with 1 parameter
void printInfo(int age)
{
cout << "Age: " << age << " years" << endl;
}
//Function with 2 parameters
void printInfo(int age, double height)
{
cout << "Age: " << age << " years, Height: " << height << " meters" << endl;
}
//Function with 3 parameters
void printInfo(int age, double height, string name)
{
cout << "Age: " << age << " years, Height: " << height << " meters," << " Name: " << name << endl;
}
int main() //main function
{
printInfo(21); // function with 1parameter
printInfo(28, 5.8); // function with 2 parameters
printInfo(32, 6.2, "John"); //function with 3 parameters
return 0;
}
Output:
Age: 21 years
Age: 28 years, Height: 5.8 meters
Age: 32 years, Height: 6.2 meters, Name: John
Explanation:
In this instance, we showcase the concept of function overloading by creating three distinct printInfo functions that accept varying numbers of parameters. The output of each function is determined by the quantity of arguments provided, displaying details such as age, height, and name.
Different variations of the printInfo function are invoked with one, two, and three arguments within the main function. This showcases the concept of function overloading, enabling the presence of multiple functions sharing the same name but having distinct parameters.
2. Function Overloading Based on Different Parameter Types:
Within this approach, numerous functions share identical names but possess varying data types in their parameters. This feature enables a function to manage a diverse range of inputs while upholding a uniform interface, ultimately improving the code's readability and flexibility.
Syntax:
It has the following syntax.
void displayData(int num); // integer parameter function
void displayData(double num); // double parameter function
void displayData(string text); // a string parameter function.
C++ Function Overloading Based on Different Parameter Types Example:
Example
#include <iostream>
using namespace std; //using standard namespace
void printInfo(int num) //int number
{
cout << "An Integer value is: " << num << endl;
}
void printInfo(double num) //double function
{
cout << "The Double value is: " << num << endl;
}
void printInfo(string text) //string function
{
cout << "The String value is: " << text << endl;
}
int main() //main function
{
printInfo(27); // Call a function with int number
printInfo(7.36); // Call a function with double number
printInfo("Hello Cpp Tutorial"); // Call a function with string
return 0;
}
Output:
An Integer value is: 27
The Double value is: 7.36
The String value is: Hello Cpp Tutorial
Explanation:
In this instance, we showcase function overloading by utilizing distinct parameter types. The primary function invokes printInfo with a range of argument types, leading to the execution of the relevant function depending on the argument and data type. The program showcases integer, double, and string values alongside their respective labels.
3. Function Overloading Based on Different Parameter Order:
Function overloading enables multiple functions to utilize the same name provided that the parameters in each function's list vary in terms of number, type, and order. When the types of parameters remain the same but their order is altered, it is referred to as overloading based on distinct parameter sequences.
Syntax:
It has the following syntax.
void displayData(int x, double y)
{
//code block
}
void displayData(double x, int y)
{
//code block
}
C++ Function Overloading Based on Different Parameter Orders Example:
Example
#include <iostream>
using namespace std; //using standard namespace
void printInf(int a, double b) //int and double function
{
cout << "Integer value is: " << a << ", Double value is: " << b << endl;
}
void printInfo(double a, int b) //double and int function
{
cout << "Double value is: " << a << ", Integer value is: " << b << endl;
}
int main()
{
printInf(21, 5.4); // call int and double value
printInf(7.84, 19); // Call double and int value
return 0;
}
Output:
Integer value is: 21, Double value is: 5.4
Double value is: 7.84, Integer value is: 19
Explanation:
In this instance, we showcase function overloading through the creation of two printInf functions, each accepting similar parameters but in varying sequences. The initial version displays an ID as an integer and a score as a double, while the alternative version showcases a rating as a double and a count as an integer.
Use Cases for Function Overloading in C++:
Several use cases for function overloading in C++ are as follows:
- Mathematical Operations: Overloading functions like calculate for several parameter types (including int, float, and double) ensures precision and efficiency. It prevents loss of accuracy when performing arithmetic on different data types.
- Handling Different Data Types: It improves code readability by enabling a single function name to handle several data types (including print(int), print(double), and print(string)).
- Varying Number of Parameters: Functions (including logMessage(string), and logMessage(string, int)) are flexible enough to take different numbers of arguments.
- Custom data processing: It allows for the specific handling of different data structures, such as sort(vector) and sort(vector). It enables the implementation of generic algorithms that handle many kinds of data.
- Improving Code Maintainability: It reduces repetition and makes the code easier to manage and cleaner by combining related operations within a single function name. It increases reusability and reduces the possibility of errors brought on by the implementation of duplicate functions.
Main differences between Function Overloading and Operator Overloading
Several key variances between function overloading and operator overloading in C++ include the following:
| Function overloading | Operator overloading |
|---|---|
| It is possible to use various parameters in an overload of a function with the same name. | We can overload operators such as +, -, / |
| A function might have more than one execution with various parameters when it is overloaded. | Operation reliance on operands occurs when an operator is overloaded. |
| The user can call using a variety of methods. | In addition to the predetermined meaning, it enables the user to have a more expansive meaning. |
Main differences between Function Overloading and Function Overriding:
Several key distinctions between function overloading and function overriding in C++ are outlined below:
| Function overloading | Function overriding |
|---|---|
| It allows the programmer to have many functions with the same name but distinct arguments. | Method overriding occurs when two methods with the same name and parameters are present in different classes, one in the parent and one in the child. |
| They have the same scope. | They have different scopes. |
| Even without inheritance, function overloading is possible. | It only happens when there is inheritance. |
C++ Function Overloading MCQS:
- What is Function Overloading in C++?
- Using different function names for similar tasks.
- Defining multiple functions with the same name but different parameters.
- Using a single function to handle multiple data types.
- Defining functions with identical signatures.
- Which of the following option is not an instance of Function Overloading?
- void func(int a); and void func(float a);
- void func(int a, double b); and void func(double a, int b);
- int func(int a); and void func(int a);
- void func; and void func(int a, int b);
- What happens if two overloaded functions contain the same parameter types but different return types?
- It causes a compilation error.
- The function with the larger return type is called.
- The function with the smaller return type is called.
- The compiler picks one at random.
- Which of the following option shows a correct example of function overloading in C++?
- void display(int a); void display(int a, double b);
- int display(int a); double display(int a);
- void show(int a); void show(float b);
- Both A and C
- What is the main advantage of Function Overloading?
- It improves the code readability.
- It reduces the number of functions.
- It eliminates function parameters.
- It increases the execution speed.