OOPS - [C++ Default Function Arguments]

♠ Posted by Unknown in at 10:20

Default Function 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 compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values.

Default argument is checked for type at the time of declaration and evaluated at the time of call. One important point to note is that only the trailing arguments can have default values. It is important to note that we must add defaults from right to left. We cannot provide a default value to a particular argument in the middle of an argument list. Some example of function declaration with default values are:

                        int mul(int I, int j = 5, int k = 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

Example:

#include<iostream.h>
#include<conio.h>
#include<iomanip.h>
float value(float p, int n, float r = 0.15);
void printline(char ch = '*', int len = 40);

void main()
{
      float amount;
      clrscr();
      printline(); //Use default values for Argument
      amount = value(5000.00, 5); //Default for 3rd Argument
      cout<<"\n\tFinalValue = "<<amount<<endl;
      printline('='); //Use default value for 2nd Argument
      getch();
}

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<<endl;
    }

0 comments:

Post a Comment