Functions with Default Arguments
- C++ also allows one to introduce functions with default arguments.
-
In the function prototype, arguments having default values must appear after all the other arguments without default values, and their default values must be specified.
-
The function definition should be the same whether or not default arguments are used.
-
The function call may provide as few arguments as there are non-default arguments, up to the total number of parameter.
-
The arguments will be applied to the non-default arguments in order, then to the default arguments up to the total
number of arguments.
-
//This program illustrates the use of a function with default arguments.
#include <iostream>
using namespace std;
void drawLine(int len, char ch = '/', int nls = 1);
// Draws a horizontal line of length len starting at the cursor
// using the character ch, followed by nls newline characters.
// The default character is '/'.
// The default number of newline is 1.
int main( )
{
// Must at least specify the number of character to print.
// The 2 default arguments take on their default values.
drawLine(50);
// The second default argument take on its default value.
drawLine(30,'#');
// Want the second default argument to take on a non-default value.
// The first default argument must then be specified
// even though it take its default value.
drawLine(50,'/',2);
// Shows a line with nls = 0 (no newline)
drawLine(30,'@',0);
// The next line starts where the previous line ends.
drawLine(20,'*');
// A long line with nls = 5 (generating 4 blank lines).
drawLine(79,'=',5);
return 0;
}
void drawLine(int len, char ch , int nls)
{
for (int n = 1; n <= len; n++)
cout << ch;
for (n = 1; n <= nls; n++)
cout << '\n';
}