Dynamic Constructor in C++ with Examples
When allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is known as dynamic constructor. By using this, we can dynamically initialize the objects.
Explanation: In this we point data member of type char which is allocated memory dynamically by new operator and when we create dynamic memory within the constructor of class this is known as dynamic constructor.
1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
Explanation: In this program we have created array of object dynamically. The first object is ptr, second is ptr and so on . For each object creation default constructor is called and for each object memory is allocated to pointer type variable by new operator.
Explanation: In this integer type pointer variable is declared in class which is assigned memory dynamically when the constructor is called. When we create object obj1, the default constructor is called and memory is assigned dynamically to pointer type variable and initialized with value 0. And similarly when obj2 is created parameterized constructor is called and memory is assigned dynamically.