Dynamic Constructor in C++
Dynamic constructors create dynamic memory by using a dynamic memory allocator new within the constructor. This allows us to initialize objects dynamically. The term dynamic constructor is used when memory allocation is done dynamically inside a constructor using the keyword new.
The dynamic constructor will not create any memory for the object. However, it creates a memory block that the objects could access.
Example-1:
#include<iostream>
using namespace std;
class example
{
const char* ptr;
public:
// default constructor
example()
{
// allocating memory at run time by using the new keyword
ptr = new char[15];
ptr = "Hi from example constructor ";
}
void display()
{
cout << ptr;
}
};
int main()
{
example obj1;
obj1.display();
}
Output:
Explanation:
In the above example, we have created a class example inside which we have given a constructor with the same name as the class name. We have declared a pointer for a character. We have used the pointer and created a char using the pointer.
Example-2:
#include<iostream>
using namespace std;
class example
{
int num1;
int num2;
int *ptr;
public:
// default constructor (here, it is a dynamic constructor also)
example()
{
num1 = 0;
num2 = 0;
ptr = new int;
}
//dynamic constructor with parameters
example(int x, int y, int z)
{
num1 = x;
num2 = y;
ptr = new int;
*ptr = z;
}
void display()
{
cout << num1 << " " << num2 << " " << *ptr;
}
};
int main()
{
example obj1;
example obj2(20, 50, 1);
obj1.display();
cout << endl;
obj2.display();
}
Output:
Explanation:
In the above example, we used the dynamic constructor and passed a few arguments. Unlike in the previous example, we have passed a few arguments.