Default parameters can be added to the end of a parameter list. If a value is to be passed to a particular default parameter, then the preceding default parameters must also be passed. For example:
// Example Default Parameters void decrement(int &aValue, int amount=1) { aValue = aValue - amount; } // To use this method, some examples int x = 10; decrement(x,3); // x now has the value 7 decrement(x); // x now has the value 6
The full source code for this example is listed in
DefaultParameters.cpp
To prevent modification of the parameters (when required), the use of constant parameters
is good coding practice. It is particularly important when passing parameters by reference that
you do not wish modified. Use the const
keyword in the parameter list:
// Example Constant Parameters void decrement(const int &aValue, int amount=1) { aValue = aValue - amount; // NOT ALLOWED }
The full source code for this example is in
ConstantParameters.cpp
In this example the code segment has been modified to set the passed value to constant. When the value is modified it causes an error (at compile time). This code will not compile, and even if it did, it would be pointless having a decrement method that could not decrement.
© 2006
Dr. Derek Molloy
(DCU).