VOOZH about

URL: https://www.geeksforgeeks.org/cpp/dynamic-initialization-of-object-in-c/

⇱ Dynamic initialization of object in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Dynamic initialization of object in C++

Last Updated : 23 Jul, 2025

In this article, we will discuss the Dynamic initialization of objects using Dynamic Constructors.

  • Dynamic initialization of object refers to initializing the objects at a run time i.e., the initial value of an object is provided during run time.
  • It can be achieved by using constructors and by passing parameters to the constructors.
  • This comes in really handy when there are multiple constructors of the same class with different inputs.

Dynamic Constructor:

  • The constructor used for allocating the memory at runtime is known as the dynamic constructor.
  • The memory is allocated at runtime using a new operator and similarly, memory is deallocated at runtime using the delete operator.

: 

Approach:

  1. In the below example, new is used to dynamically initialize the variable in default constructor and memory is allocated on the heap.
  2. The objects of the class geek calls the function and it displays the value of dynamically allocated variable i.e ptr.

Below is the program for dynamic initialization of object using new operator:


Output
10

:
Approach:

  1. In the below code, delete is used to dynamically free the memory.
  2. The contents of obj1 are overwritten in the object obj2 using assignment operator, then obj1 is deallocated by using delete operator.

Below is the code for dynamic deallocation of the memory using delete operator.


Output
Value: 10
Value: 10

Below C++ program is demonstrating dynamic initialization of objects and calculating bank deposit:

Output:

Deposited amount (float):209.101

Deposited amount (integer):220.5
Comment