How to Use Default Arguments in Function Overloading in C++?
Last Updated :
19 Feb, 2024
In C++, we can provide the default values for the input arguments into the functions and it is also supported in function overloading. In this article, we will learn how to use default arguments in function overloading in C++.
Default Arguments in Function Overloading in C++
We can define the default value in function overloading as we do it in the main function. But the problem occurs in situations where there are multiple matching function definitions for a function call and the compiler cannot decide which function body to execute.
For Example, see the function overloading of:
int func(int a) { //body }
int func(int a, int b = 10) { // body }
Both of the above functions can be called using the call func(10) leading to ambiguity issues.
C++ Program to Use Default Arguments in Function Overloading
The below example demonstrates how we can use default arguments in function overloading in C++.
C++
#include <iostream>
using namespace std;
void display( int a, int b, int c)
{
cout << "Values: " << a << " " << b << " " << c << endl;
}
void display( int a, int b = 10)
{
cout << "Values: " << a << " and " << b << endl;
}
int main()
{
display(5);
display(5, 20);
display(10, 15, 20);
return 0;
}
|
Output
Values: 5 and 10
Values: 5 and 20
Values: 10 15 20
Note: When using default arguments with function overloading make sure that any call to an overloaded function is unambiguous and compiler must be able to select the correct function based on the function call.
Share your thoughts in the comments
Please Login to comment...