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.
Dynamic Allocation:
Approach:
- In the below example, new is used to dynamically initialize the variable in default constructor and memory is allocated on the heap.
- 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:
C++
#include <iostream>
using namespace std;
class geeks {
int * ptr;
public :
geeks()
{
ptr = new int ;
*ptr = 10;
}
void display()
{
cout << *ptr << endl;
}
};
int main()
{
geeks obj1;
obj1.display();
return 0;
}
|
Dynamic Deallocation:
Approach:
- In the below code, delete is used to dynamically free the memory.
- 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.
C++
#include <iostream>
using namespace std;
class geeks {
int * ptr;
public :
geeks()
{
ptr = new int ;
*ptr = 10;
}
void display()
{
cout << "Value: " << *ptr
<< endl;
}
};
int main()
{
geeks* obj1 = new geeks();
geeks* obj2 = new geeks();
obj2 = obj1;
obj1->display();
obj2->display();
delete obj1;
return 0;
}
|
OutputValue: 10
Value: 10
Below C++ program is demonstrating dynamic initialization of objects and calculating bank deposit:
C++
#include <iostream>
using namespace std;
class bank {
int principal;
int years;
float interest;
float returnvalue;
public :
bank() {}
bank( int p, int y, float i)
{
principal = p;
years = y;
interest = i/100;
returnvalue = principal;
cout << "\nDeposited amount (float):" ;
for ( int i = 0; i < years; i++) {
returnvalue = returnvalue
* (1 + interest);
}
}
bank( int p, int y, int i)
{
principal = p;
years = y;
interest = float (i)/100;
returnvalue = principal;
cout << "\nDeposited amount"
<< " (integer):" ;
for ( int i = 0; i < years; i++) {
returnvalue = returnvalue
* (1 + interest);
}
}
void display( void )
{
cout << returnvalue
<< endl;
}
};
int main()
{
int p = 200;
int y = 2;
int I = 5;
float i = 2.25;
bank b1(p, y, i);
b1.display();
bank b2(p, y, I);
b2.display();
return 0;
}
|
Output:
Deposited amount (float):209.101
Deposited amount (integer):220.5