You are hereFunctions in C++ - Advanced features
Functions in C++ - Advanced features
The discussion and concepts discussed in the first tutorial on functions hold equally true for C++ as well.
However C++ functions supports some additional features as well. This tutorial deals with these features.
Call by reference
apart from the method discussed in the first tutorial (highlighing the use of pointer arguements) , C++ provides the '&'(referential) operator for calling by reference.
Syntax
return-type function-name(data-type & arguement_name);
function definition
return-type function-name(data-type & arguement_name)
{
inside the body , the aguement is to be used as any other variable(not as pointer variable)
}
function call
function_name(arguement name);
//the variable is passed like any other variable of its data type and as an address
Example :: SWAP program revisited
Default arguments
C++ provides the option of providing default values to the arguments being passed to a function.
Consider the example
IMPORTANT
all the parameters with default values should lie to the right in the signature list i.e. the default arguments should be the trailing arguments—those at the end of the list.
when a function with default arguments is called, the first argument in the call statement is assigned to the first argument in the definition, the 2nd to 2nd and so on.
This becomes more clear from the last call to sum() in the above example where value 10 is assigned to n and 2 is assigned to diff and not first_term.
the default argument values appear in the prototype as well as definition.
You still may omit variable names in the prototypes.
The syntax then being
int xyz(int =2,char=5);
Function overloading
c++ permits the use of two function with the same name. However such functions essentially have different argument list. The difference can be in terms of number or type of arguments or both.
This process of using two or more functions with the same name but differing in the signature is called function overloading.
But overloading of functions with different return types are not allowed.
In overloaded functions , the function call determines which function definition will be executed.
The biggest advantage of overloading is that it helps us to perform same operations on different datatypes without having the need to use separate names for each version.
Example
the above function finds the absolute value of any number int, long, float ,double.
In C, the above is implemented as a set of different function abs()-for int, fabs()-for double ,labs()-for long.
The use of overloading may not have reduced the code complexity /size but has definitely made it easier to understand and avoided the necessity of remembering different names for each version function which perform identically the same task.



