C++ has added the ability to have default arguments be defined when you declare your functions. To define a default value, you must specify the parameter name, and then assign it a value.
double circleArea(double radius = 20)
{
const double PI = 3.1415;
return PI * radius * radius;
}
If someone calls this function without passing an argument to the function, the computer will use 20 as the parameter. If they pass a argument , then that argument will be used as the parameter.
double area1 = circleArea();
double area2 = circleArea(33.2);
In some ways, this is like function overloading, but simpler to use. For example, both of the following examples are equivalent:
// overloaded example
double circleArea()
{
return circleArea(20);
}
double circleArea(double radius)
{
const double PI = 3.1415;
return PI * radius * radius;
}
// default value value example
double circleArea(double radius = 20)
{
const double PI = 3.1415;
return PI * radius * radius;
}
When calling a function with a default value, once a default value is used, then the remaining parameters must use their default value.
double boxVolume(double height = 10, double width = 10, double depth = 10)
{
return height * width * depth;
}
cout << boxVolume() << endl; // valid call
cout << boxVolume(10,20,30) << endl; // valid call
cout << boxVolume(10,20) << endl; // valid call
/// errors at this point
cout << boxVolume(,,10) << endl; // ivalid call
cout << boxVolume(10, ,20) << endl; // ivalid call
Default Arguments was originally found on Access 2 Learn