What is Dynamic Constructor in C++?
The constructor which allocates a block of memory that can be accessed by the objects at run time is known as Dynamic Constructor.
In simple terms, a Dynamic constructor is used to dynamically initialize the objects, that is memory is allocated at run time.
To define a dynamic constructor in C++, the new keyword is used. New is a keyword in C++ that is used for the dynamic allocation of memory and is used for dynamically initializing objects.
Example of Dynamic Constructor
Let us understand Dynamic constructors in C++ with the help of an example that consists of class A.
We will dynamically allocate memory to the data members inside the default constructor of class A as well as a parameterized constructor of class A and check the output.
Output:
Explanation:
We created a dynamic memory within the constructor of a class by using the New keyword.
This represents a Dynamic constructor in both the default as well as parameterized constructor.
Here, the memory allocation is done at run time, that is the values are assigned as well as the constructor is invoked at run time when the object is created.
Example Showing How a Dynamic Constructor Allocates Memory at Run Time
Output:
Explanation:
When we initialize the variable banner using New keyword, it invokes a dynamic constructor thus allocating space in the memory at runtime.
Program to Create an Array of Objects Dynamically
Let us implement a program using C++ to create an array of objects dynamically.
Output:
Explanation:
We created an array of 5 objects that calls dynamic constructors individually and memory is allocated for each object at run time.
Conclusion
- Dynamic Constructor is used to dynamically allocate memory to be accessed by objects at runtime.
- Dynamic Constructor in C++ is declared using the keyword 'new'.
- Objects can also be dynamically initialized using the 'new' keyword.