Tuesday, October 16, 2012

Default Arguments Program


When we have to define a function that will work on different no. of arguments for number of time then the solution is function overloading.But in case of overloading we have to pass the agruments again and again even if we are calling the function with same value of arguments for many time.C++ resolve this problem with the help of Default Arguments.Now if the function is called one or two or all the arguments missing,the compiler takes it value from the default agruments declare at function prototype.But the missing arguments must be the trailing arguments(those at the at of argument list).Have a look at example given below.

/*Draw boxes of different length using default arguments*/

#include<iostream.h>
#include<conio.h>
//function declaration with default arguments value.
void drawBox(int a=14,int b=23,int c=10,int d=15);
void main()
{
clrscr();
drawBox(10,20,22,40);
drawBox(8,18,24,42);
//compiler will take the missing value from default arguments.
drawBox(2,2); 
getch();
}
void drawBox(int a,int b,int c,int d)
{
int x,y;

for(x=a;x<c;x++)
  {
  gotoxy(b,x);
  cout<<'*';
  gotoxy(d,x);
  cout<<'*';

  }
for(y=b;y<=d;y++)
  {
  gotoxy(y,a);
  cout<<'*';
  gotoxy(y,c);
  cout<<'*';

  }
}