Default Arguments
C++ allows us to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared. The complier looks at the prototype to see how many arguments a function uses and alerts the program for possible default values. Here is an example of prototype (i.e function declaration) with default values:
float amount( float principal, int period, float rate=0.15);
The above prototype declares a default value of 0.15 to the argument rate. A subsequent function call like
value = amount( 5000, 7); // one argument missing
passes the value of 5000 to principal and 7 to period and then lets the function use default value of 0.15 for rate. The call
value = amount(5000, 5, 0.12); // no missing argument
passes an explicit value of 0.12 to rate.
- A default argument is checked for type at the time of declaration and evaluated at the time of call.
- Only trailing arguments can have default values. we cannot provide a default value to a particular argument in the middle of an argument list.
Examples:
int mul(int i, int j = 5, int = 10); // legal
int mul(int i =5, int j); //illegal
int mul(int i=0, int j, int k=10); //illegal
int mul(int i=2, int j=5, int k=10); //legal
- Default arguments are useful in situations where some arguments always have the same value. For example, bases of logarithm function.
- It provides a greater flexibility to the programmers.
- A function can be written with more parameters than are required for its most common application.
|
//////////////////////////[ DEFAULT ARGUMENTS]////////////////////////
# include <iostream.h>
# include <stdio.h>
int main (void )
{
float amount;
float value( float p, int n, float r = 0.15); // prototype
void printline(char ch = * , int len = 40); //prototype
printline(); //uses default values for arguments
amount=value(5000.00,5); //default for 3rd argument
cout << "\n Final value = " <<amount << "\n\n";
printline( = );
return(0);
}
/* …………………………………..function definitions …………………………………………..*/
float value ( float p, int n, float r)
{
int year =1;
float sum = p;
while (year <= n)
{
sum = sum * (1+r);
year = year +1;
}
return(sum);
}
void printline(char ch, int len)
{
for (int i = 1; i <= len; i++) cout << ch;
cout << "\n";
}
/////////////////////////////< program 4.2>////////////////////////////////
|
The output of program would be:
********************************************
Final value = 10056.786133
=======================================
Advantage of providing the default arguments are:
1- We can use default arguments to add new parameters to the existing functions.
2- Default arguments can be used to combine similar functions into one.
const Arguments
An argument to a function can be declared as count as shown below.
int strlen(const char *p);
int length(const string & s);
The qualifier const tells the compiler that the function should not modify the argument. The compiler will generate an error when this condition is violated. This type declaration is significant only when we pass arguments by reference or pointers.
Function Overloading
Overloading refers to the use of the same thing for different purpose.
C++ permits overloading of functions. This means that we can use the same function name to create functions that perform a variety of different tasks.
Using the concept of function overloading, we can design a family of functions with one function name but with different argument lists.
The function would perform different operations depending on the argument list in the function call.
The correct function to be invoked is determined by checking the number and the type of the arguments but not on function type. For example, an overloaded add( ) function handles different types of data as shown below:
//Declarations
int add(int a, int b); //prototype 1
int add(int a, int b, int c); //prototype 2
double add(double x, double y); //prototype 3
double add(int p, double q); //prototype 4
double add(double p, int q); //prototype 5
//function call
cout << add(5, 10); // uses prototype 1
cout << add(15,10.0); // uses prototype 4
cout << add(12.5, 7.5); // uses prototype 3
cout << add(5, 10, 15); // uses prototype 2
cout << add(0.75, 5); // uses prototype 5
A function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. A best match must be unique. The function selection involves the following steps:
- The compiler first tries to find an exact match in which the types of actual arguments are the same and use that function.
- If an exact match is not found, the compiler uses the integral promotions to the actual arguments, such as,
char to int
float to double
to find a match.
- When either of them fails, the complier tries to use the built-in conversions(the implicit assignment conversations) to the actual arguments and then uses the function whose match is unique. If the conversation is possible to have multiple matches, then the compiler will generate an error message. Suppose we use the following two functions:
long square(long n);
double square( double x);
A function call such as
square(10);
will cause an error because int argument can be converted to either long or double, thereby creating an ambiguous situation as to which version of square( ) should be used.
- If all of the steps fail, then the compiler will try the user-defined conversations in combinations with integral promotions and built-in conversations to find a unique match. User-defined conversations are often used in handling class objects.
|
//////////////////[ FUNCTION OVERLOADING]/////////////////////////////////
# include <iostream.h>
int volume( int); // prototype declarations
double volume( double, int); // for overloading volume ( )
long volume (long, int , int );
//………………………………..function definition …………………………………………
int volume (int s) // cube
{
return(s * s * s);
}
double volume( double r, int h) //cylinder
{
return(3.14519 * r * r * h);
}
long volume(long l, int b, int h) // rectangular box
{
return( l * b * h);
}
//----------------------------------------main function ------------------------------------------------------------
int main (void)
{
cout << volume (10); <<"\n";
cout << volume (2.5, 8 ) << "\n";
cout << volume (1000, 75 , 15);
}
////////////////////////////< PROGRAM 4.3 >//////////////////////////////////
|
The output of program would be:
1000
157.2595
112500
Overloading of the functions should be done with caution. We should not overload unrelated functions and should reserve function overloading for functions that perform closely related tasks. Sometimes, the default arguments may be used instead of overloading. This may reduce the number of functions to be defined.
Questions
- State whether the following statements are TRUE or FALSE..
a. A function argument is a value returned by the function to the calling program.
b.When arguments are passed by value, the function works with the original arguments in the calling program.
c. When a function returns a value, the entire function call can be assigned to a variable.
d. A function can return a value by reference.
e. When an argument is passed by reference, a temporary variable is created in te calling program to hold the argument value.
f. It is not necessary to specify the variable name in the function prototype.
- What are the advantages of function prototypes in C++?
- When will you make a function inline? Why?
- When do we need to use default arguments in a function?
- What do you meant by overloading of a function? When do we use this concept?
- The effect of a default argument can be alternatively achieved by overloading. Discuss with an example.
المادة المعروضة اعلاه هي مدخل الى المحاضرة المرفوعة بواسطة استاذ(ة) المادة . وقد تبدو لك غير متكاملة . حيث يضع استاذ المادة في بعض الاحيان فقط الجزء الاول من المحاضرة من اجل الاطلاع على ما ستقوم بتحميله لاحقا . في نظام التعليم الالكتروني نوفر هذه الخدمة لكي نبقيك على اطلاع حول محتوى الملف الذي ستقوم بتحميله .