Open In App

How to Use Default Arguments in Function Overloading in C++?

Last Updated : 19 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C++ program to use default argument in function
// overloading
#include <iostream>
using namespace std;
  
// Function without default arguments
void display(int a, int b, int c)
{
    cout << "Values: " << a << " " << b << " " << c << endl;
}
  
// Overloaded function with default arguments
void display(int a, int b = 10)
{
    cout << "Values: " << a << " and " << b << endl;
}
  
int main()
{
    display(5); // display(int a,int b=10) is called and
                // default value 10 is used here because
                // second arguement is missing
  
    display(5, 20); // display(int a,int b=10) is called but
                    // two arguements are passed so default
                    // value is not used here
  
    display(10, 15, 20); // overloaded function display(int
                         // a,int b,int c) is called
  
    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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads