Page 129 - DCAP404 _Object Oriented Programming
P. 129

Object-oriented Programming




                    Notes          6.3 Dynamic Constructors

                                   Allocation of Memory during the creation of objects can be done by the con structures too.
                                   The memory is saved as it allocates the right amount of memory for each object (Objects are not
                                   of the same size). Allocation of memory to objects at the time of their construction is known as
                                   dynamic construction of objects. New operator is used to allocate memory.
                                   The following program concatenates two strings. The constructor function initializes the strings
                                   using constructor function which allocates memory during its creation.
                                   #include  <iostream.h>
                                   #include  <string.h>
                                   class  string
                                   {
                                          char  *  name;
                                          intlength;
                                          public:
                                          string  0
                                   {
                                          length  =  0;
                                          name  =  new  char  [length  =  1];
                                   };
                                   string  (char*s)
                                   {
                                   length  =  strlen  (s);
                                   name  =  new  char  [length  +  1];
                                   strcpy(name,s  );
                                   };
                                   void  display  (void)
                                   {
                                          cout<<“\n  Name  :-  “<<name;
                                   };
                                   void  join  (string  &  a,  string  &  b)
                                   {
                                          length  =  a.length  +  b.length;
                                          delete  name;
                                          name  =  new  char  [length  +  1];
                                          strcpy  (name,a.name);
                                          strcat  (name,”  “);
                                          strcat  (name,b.name);
                                   };
                                   };
                                   main()




          122                               LOVELY PROFESSIONAL UNIVERSITY
   124   125   126   127   128   129   130   131   132   133   134