Home / Cplusplus / Dynamic Constructors In C++

Dynamic Constructors In C++

The constructors 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 when the objects are not of the same size, thus resulting in the saving of memory.
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.
Here we are going to introduce the destructor which is often not necessary. You can use it to do some calculation whenever an instance is destroyed or output some text for debugging.
But if variables of the instance point towards some allocated memory then the role of the destructor is essential: it must free that memory!
Here is an example of such an application:
Out put of the program
Definition: The destructor is a member function that is invoked when an object goes out of scope. It should free any dynamically allocated memory that the object was using.