Dynamic constructor
The constructor can be used to allocate the memory dynamically while creating the objects. This will enable the system to allocate the right amount of memory for each object when the objects are not of the same size, thus saving memory.
Allocation of memory to the objects at the time of their construction is known as dynamic construction of objects.
The memory is allocated with the help of new operator.
Example of dynamic constructor
#include<iostream> #include<conio.h> #include<string.h> using namespace std; class string1 { private: char *name; int len; public: string1(); string1(char *s); void display(); void join(string1 A,string1 B); }; string1::string1() { len=0; name=new char[len+1]; name[0]='\0'; } string1::string1(char *s) { len=strlen(s); name=new char[len+1]; strcpy(name,s); } void string1::display() { cout<<"Name is "<<name<<" len is "<<len<<endl; } /*void string1::join(string A,string B) { len=A.len+B.len; name=new char[len+1]; strcpy(name,A.name); strcat(name,B.name); } */ //if space is to be given in between names then it can be modified as void string1::join(string1 A,string1 B) { len=A.len+B.len; name=new char[len+1+1]; strcpy(name,A.name); strcat(name," "); strcat(name,B.name); } int main() { char *first="Hello"; //char first[]="Hello"; char first[6]="Hello"; string1 n1(first); string1 n2="Kamlesh"; string1 n3="Kumar"; string1 n4,n5; n4.join(n1,n2); n5.join(n4,n3); n1.display(); n2.display(); n3.display(); n4.display(); n5.display(); getch(); return(0); }
Output:
Name is Hello len is 5
Name is Kamlesh len is 7
Name is Kumar len is 5
Name is Hello Kamlesh len is 12
Name is Hello Kamlesh Kumar len is 17