Introduction:
In this article ,we are going to learn default arguments in c++ along with their functioning by taking the help of examples.In C++ programming language, we are allowed to provide default values in the place of function parameters If a function which is having default arguments in c++ is called and arguments are not passed, then the default parameters will come into use. However, if we will pass the arguments while calling the function, the default arguments will get ignored.
Example: Default Argument
#include <iostream>
using namespace std;
// defining the default arguments
void ridisplay(char = '%', int = 3);
int main() {
int ricount = 5;
cout << "No argument is being passed: ";
// %, 3 are going to be parameters
ridisplay();
cout << "First argument is being passed: ";
// &, 3 are going to be parameters
ridisplay('&');
cout << "Both arguments are being passed: ";
// @, 5 are going to be parameters
ridisplay('@', ricount);
return 0;
}
void ridisplay(char rc, int ricount) {
for(int ri = 1; ri <= ricount; ++ri)
{
cout << rc;
}
cout << endl;
}
default arguments in c++
Output:
No argument is being passed: %%%
First argument is being passed: &&&
Both arguments is being passed: @@@@@
Here is the description of how this program works:
ridisplay() is being called without having any arguments passed. In the present case, ridisplay() is supposed to use both the default parameters rc = ‘%’ and n = 1.
ridisplay(‘#’) is being called with the presence of only one argument. In the present case, the first argument becomes ‘&’. The second default parameter n = 1 is goint to stay retained.
ridisplay(‘@’, count) is being called along with both the arguments. In the present case, default arguments are not going to be used.
We are also allowed to define the default parameters which are present in the function definition itself. The following program is going to be equivalent to the one above.
#include <iostream>
using namespace std;
void ridisplay(char rc = '*', int ricount = 3) {
for(int ri = 1; ri <= ricount; ++ri) {
cout << rc;
}
cout << endl;
}
int main() {
int ricount = 5;
cout << "No argument is being passed: ";
// %, 3 is going to be parameters
ridisplay();
cout << "First argument is being passed: ";
// &, 3 are going to be parameters
display('&');
cout << "Both argument are being passed: ";
// @, 5 are going to be parameters
display('@', ricount);
return 0;
}
Things which are to be remembered:-
If we are going to provide some default value for a particular parameter, all the subsequent parameters are also supposed to have the default values. For e.g.,
// Invalid
void riadd(int ra, int rb = 3, int rc, int rd);
// Invalid
void riadd(int ra, int rb = 3, int rc, int rd = 4);
// Valid
void riadd(int ra, int rc, int rb = 3, int rd = 4);
// Invalid code
int main() {
// function call
ridisplay();
}
void ridisplay(char rc = '*', int ricount = 5) {
// your code
}