Default Arguments
- When a function prototype specifies a list of parameters, argument
values are
explicitly passed to the function when an appropriate function call is
made.
- However, not all functions may require argument values. For example,
consider
the following function prototype and its associated function call:
void PrintIt(); // Prototype
PrintIt(); // Function call
void PrintIt(){
cout << "Printed It" << endl;
}
Because the prototype specifies no arguments, when the function is called
no values are passed to the function
- In addition to the above two types of function calls, C++ provides a
third
type of function call - function calls with default argument values.
Consider the
following code fragment:
int ComputeInterest(float i=0.05); // Prototype
ComputeInterest(); // Function call
int ComputeInterest(float i){ // Note: no default value is specified here
// The function implementation goes here...
}
Even though the function call does not explicitly pass an argument value
to
the function, the compiler automatically inserts the argument value in the
function
call.
- NOTE: The default arguments must be the rightmost (trailing)
arguments
in a function's parameter list. For example:
int ComputeInterest(float , int , float interest=0.05);
.
.
.
ComputeInterest(principal, period); // default interest is 0.05
Overloading
- One of the ways in which C++ supports polymorphic behavior is through
the use of overloaded functions
- Function overloading refers to the concept of a single function name
with
multiple implementations. In other words, in C++ it is perfectly
legitimate to
have more than one implementation for the same function. When a function
call
is made, the compiler associates each function call with the appropriate
implementation
- The compiler distinguishes between each implementation of an
overloaded
function based on the signatures of each version of the function.
A
function's signature is defined by its name and parameter
list
- NOTE: Each version of the overloaded function must have a unique
signature
- When a program that contains an overloaded function is compiled, the
compiler
generates unique function name symbols for each version of the overloaded
function. This process is called name mangling. Each function
call
is then associated with the appropriate name mangled function
implementation
- Example...
- NOTE: Defining two versions of an overloaded function - one with
an
empty parameter list and the other with only default arguments will cause
an
ambiguity for the compiler. Example...