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. 


In the program below, the class cube is so defined that the length, width and height of the cube are all set to zero if not defined explicitly. So, in the main function we have defined two Objects namely a and b. The variables for are defined to be 2, 3, and 4 through the constructor. But the variables of b in the Object constructor have not been given any values.   So what happens is that the values for length, width and height are all set to zero through the Default Argument Constructor. When we print the values of their areas, we get 24 and 0 for the Objects a and b respectively. 


#include <iostream.h>
#include <conio.h>

class cube
{
      int x, y, z;
      public:
      cube(int i=0, int j=0, int k=0)
      {
            x=i;
            y=j;
            z=k;
      }

      int volume()
      {
            return x*y*z;
      }
};

int main()
{
      clrscr();
      cube a(2,3,4), b;
      cout << a.volume() << endl;
      cout << b.volume();
      getch();
      return 0;
}

The Output for the code above is shown below as tested on the Turbo C++ Compiler.

No comments:

Post a Comment

Custom Search