Showing posts with label Default Argument. Show all posts
Showing posts with label Default Argument. Show all posts

Default Argument Constructor in C++


This program elegantly describes the Default Argument Constructor used in C++. This type of constructor can be well used to replace the usual constructors that we create. These constructors are designed to simply give the class variables some valid value even if  a value has not been assigned in the Object declaration and initialization inside main(). 

To do this, simply write the value of the variable that you want to initialize the variable with. Now if in case a new value is assigned in the Object initializer, this default defined value will be overridden with the new value. Therefore explicit as well as implicit assigning is supported. 

Default Argument


#include <iostream.h>
#include <conio.h>
/* Default indent to -1. This value tells the function
to reuse the previous value. */

void iputs(char *str, int indent = -1);

int main()
{
      clrscr();
      iputs("Hello there", 10);
      iputs("This will be indented 10 spaces by default");
      iputs("This will be indented 5 spaces", 5);
      iputs("This is not indented", 0);
      getch();
      return 0;
}

void iputs(char *str, int indent)
{
      static i = 0; // holds previous indent value
      if(indent >= 0)
      i = indent;
      else // reuse old indent value
      indent = i;
      for( ; indent; indent--) cout << " ";
      cout << str << "\n";
}
Custom Search