3.08 Method Parameters


Default Parameters

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

Constant Parameters

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.



These notes are copyright Dr. Derek Molloy, School of Electronic Engineering, Dublin City University, Ireland 2013-present. Please contact him directly before reproducing any of the content in any way.
ċ
ConstantParameters.cpp
(0k)
Derek Molloy,
19 Oct 2013, 04:56
ċ
DefaultParameters.cpp
(0k)
Derek Molloy,
19 Oct 2013, 04:56
Comments