Object Oriented Programming - Old Questions

5. What is the principle reason for using default arguments in the function? Explain how missing arguments and default arguments are handled by the function simultaneously?

5 marks | Asked in 2075

A function can be called without specifying all its arguments. But it does not work on any general function. The function declaration must provide default values for those arguments that are not specified. When the arguments are missing from function call , default value will be used for calculation.

Example:

#include <iostream>

using namespace std;

int sum(int a, int b=10, int c=20);

int main(){

   cout<<sum(11)<<endl;   /* In this case a value is passed as 11 and b and c values are taken from default arguments.*/

   cout<<sum(11, 12)<<endl;   /* In this case a value is passed as 11 and b value as 12, value of c values is taken from default arguments.*/

   cout<<sum(11, 12, 13)<<endl;  /* In this case all the three values are passed during function call, hence no default arguments have been used.*/

   return 0;

}

int sum(int a, int b, int c){

   int z;

   z = a+b+c;

   return z;

}