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 when the function is called. For example:
#include <iostream>
using std::cout;
using std::endl;
void rectangle_area(int = 3, int = 5); // Default value for width is 3, default value for height is 5
int main()
{
cout << rectangle_area() << endl; // Calls rectangle_area(3, 5), so this prints 15.
cout << rectangle_area(6) << endl; // Calls rectangle_area(6, 5), so this prints 30.
cout << rectangle_area(2, 6) << endl; // Neither default value used, so this prints 12.
return 0;
}
int rectangle_area(int width, int height)
{
return width * height;
}
Overloaded operator functions typically can not have default arguments.
Default arguments are often used with constructors. A constructor with default values for all of its arguments can serve as a default constructor. For example:
class Date
{
private:
int month;
int day;
int year;
public:
Date(int = 1, int = 1, int = 1900); // Serves as a default constructor.
...
};
Date::Date(int month, int day, int year)
{
this->month = month;
this->day = day;
this->year = year;
}
...
Since the Date
constructor has default values for all three of its arguments, there is no need to write a separate default constructor:
int main()
{
Date d1; // Date object initialized to 1/1/1900.
Date d2(10); // Date object initialized to 10/1/1900.
Date d3(4, 23); // Date object initialized to 4/23/1900.
Date d4(12, 7, 1941); // Date object initialized to 12/7/1941.
...
return 0;
}
If not all of a function's arguments have default values, the ones that do typically must be the trailing arguments in the argument list.
void f(int, int = 2, int = 3); // Default values are for trailing arguments, so this is okay.
void g(int = 1, int = 2, int); // Error: default values supplied for first two arguments.
void h(int, int = 3, int); // Error: default value supplied only for middle argument.
(There are some exceptions to this rule, particularly when it comes to more advanced template functions.)