Pages - Menu

DYNAMIC CONSTRUCTOR

The constructor can also be used to allocate memory while creating objects. This will enable the system to allocate the right amount of memory for each object. Allocation of memory to objects at the time of their construction is known as dynamic construction of objects. The memory is allocated with the help of the new operator.

Program: illustrate the working of dynamic constructors:

#include<iostream.h>
 class  Sample
     {
               char  *name;
               int  length; 
       public:
                Sample( )
                  {
                        length = 0;
                        name = new char[ length + 1];
                   }


               Sample ( char  *s )
                  {
                        length = strlen(s);
                        name = new char[ length + 1 ];
                        strcpy( name , s );
                   }
               void  display( )
                 {
                        cout<<name<<endl;
                  }
             };
          int  main( )
            {
                        char  *first = “ C++ “;
                        Sample  S1(first), S2(“ABC”), S3(“XYZ”);
                        S1.display( );
                        S2.display( );
                        S3.display( );
                        return 0;
             }
           
RESULT :                    
                    C++
                    ABC
                    XYZ

Other recommended posts of Constructor and Destructor

No comments:

Post a Comment