Javatpoint Logo
Javatpoint Logo

Dynamic Initialization of Objects in C++

In this context, we'll talk about using dynamic constructors to initialise objects.

The term "dynamic initialization of an object" refers to initialising an object during runtime, or giving it its initial value then. It can be done by utilizing constructors and providing them with parameters. It is quite useful when a class has many constructors, each with a different set of inputs.

Dynamic Constructor:

The term "dynamic function Object() { [native code] }" refers to the function Object() { [native code] } that is used to allocate memory during runtime.

The new operator is used to allocate memory at runtime, whereas the delete operator is used to deallocate memory at runtime.

Dynamic Allocation:


In the example below, memory is allocated on the heap and a variable's default function Object() { [native code] } is dynamically initialised using new.

The function is called by objects of the class "jtp" which then outputs the value of the ptr dynamically allocated variable.

The software for dynamic object initialization using the new operator is shown below:



Dynamic Deallocation:


To dynamically release the memory in the code below, use delete. Assignment operator is used to overwrite the contents of object obj1 in object obj2, and delete operator is used to deallocate object obj1.

The code for utilising the delete operator to dynamically deallocate memory is provided below.


Value: 10
Value: 10

The C++ program below shows how to dynamically initialise objects and calculate bank deposits:


Deposited amount (float):330.211

Deposited amount (integer):357.305


In this example, we have a "Student" class here, and it has two private data members.

1) rNo - to keep track of the roll number

2) use a perc function to save a percentage.


Enter roll number to initialize the object: 20
Enter percentage to initialize the object: 40
After initializing the object, the values are...

Roll number: 20
Percentage: 40%
Enter roll number: 30
Enter percentage: 50
Roll number: 30
Percentage: 50%

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA