Page 130 - DCAP404 _Object Oriented Programming
P. 130

Unit 6: Constructors and Destructors




          {                                                                                     Notes
                 char  *  FirstName=  “Mohan”;
                 string  Fname(First  name);
                 string  Mname(“Kumar”);
                 string  Sname(“Singh”);
                 string  Halfname,  Fullname;
          //Joining  FirstName  with  Surname

          Halfname.join  (Fname,  Sname);
          //Joining  Firstname  with  Middlename  &  Surname
          Fullname.join  (Halfname,  Mname);
          Fname.display  ();
          Mname.display  ();
          Sname.display  ();
          Halfname.display();

          Fullname.displayO();
          }
          You  should  see  the  following  output.
          /*
                 Name  :-  Ram
                 Name  :-  Kumar
                 Name  :-  Singh
                 Name:-  Mohan  .Singh  Name  :-  Mohan.Singh  .Kumar
          */
          The above program uses new operator to allocate memory. The first constructor is an empty
          constructor that allows us to declare an array of string. The second constructor initializes length
          of the string, allocates necessary space for the string to be stored and creates the string itself. The
          member function join ( ) concatenates 2 strings.
          It actually adds the length of 2 strings and then allocates the memory for the combined string.
          After that the join function uses inbuilt string functions strcpy & strcat to fulfil the action.
          The output of the program will be in Full Name and Half name.
          That is Mohan Singh Kumar and Ram Singh respectively.

          Another example of the dynamic constructor is the matrix program. In two Dimensional matrix
          we need to allocate the memory for the values to be stored in. Using constructor we can allocate
          the memory for the matrix.





              Task  ’Basically, it’s a way of constructing an object based on the run-time type of some
             existing object.’ Explain.





                                           LOVELY PROFESSIONAL UNIVERSITY                                   123
   125   126   127   128   129   130   131   132   133   134   135