Default Arguments in C++

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the caller of the function doesn’t provide a value for the argument with a default value.

Following is a simple C++ example to demonstrate the use of default arguments. We don’t have to write 3 sum functions, only one function works by using default values for 3rd and 4th arguments.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
  
// A function with default arguments, it can be called with 
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z=0, int w=0)
{
    return (x + y + z + w);
}
  
/* Driver program to test above function*/
int main()
{
    cout << sum(10, 15) << endl;
    cout << sum(10, 15, 25) << endl;
    cout << sum(10, 15, 25, 30) << endl;
    return 0;
}
chevron_right

Output:

25
50
80

When Function overloading is done along with default values. Then we need to make sure it will not be ambiguous.
The compiler will throw error if ambiguous. Following is the modified version of above program.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream> 
using namespace std; 
  
// A function with default arguments, it can be called with 
// 2 arguments or 3 arguments or 4 arguments. 
int sum(int x, int y, int z=0, int w=0) 
    return (x + y + z + w); 
int sum(int x, int y, float z=0, float w=0) 
    return (x + y + z + w); 
/* Driver program to test above function*/
int main() 
    cout << sum(10, 15) << endl; 
    cout << sum(10, 15, 25) << endl; 
    cout << sum(10, 15, 25, 30) << endl; 
    return 0; 
}
chevron_right

Error:



prog.cpp: In function 'int main()':
prog.cpp:17:20: error: call of overloaded 
'sum(int, int)' is ambiguous
  cout 

Key Points:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Invalid because z has default value, but w after it 
// doesn't have default value
int sum(int x, int y, int z=0, int w)
chevron_right

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.





Article Tags :
Practice Tags :