Dynamic Initialization of Objects
Class objects may be dynamically initiated. In other words, the initial values of an object may be provided during run time.
An advantage of dynamic initialization is that we can supply different initialization formats, using overloaded constructors. This provides the flexibility of using different formats of data at run-time depending on the situation. Since the values of m and n are not known till the execution.
Dynamic Constructor
This constructor is used to assign memory to run objects is called a dynamic constructor. Memory allocation to objects is assigned using a new operator. This will allow the system to assign the right amount of memory to each object when the objects are not of the same size.
Example Program:
#include <iostream> #include<string.h> using namespace std; class String { private: char *name; int length; public: String() { length = 0; name = new char[length+1]; } String(char *s) { length = strlen(s); name = new char[length+1]; strcpy(name,s); } void display() { cout<<name<<endl; } void join(String &a, String &b) { length = a.length+b.length; delete name; name=new char[length+1]; strcpy(name,a.name); strcpy(name,b.name); } }; int main() { String S1("Gitam "); String S2("University"); String S3; S3.join(S1,S2); S3.display(); return 0; }
Output:
