Dynamic Constructor in C++ with Examples
Constructor can allocate dynamically created memory to the object and thus object is going to use memory region which is dynamically created by the constructor.
In simple words, You can say that whenever allocation of memory is done dynamically using new inside a constructor, it is called dynamic constructor.
When you use dynamic memory allocator new inside the constructor to create dynamic memory, it is called dynamic constructor.
By using dynamic constructor in C++, you can dynamically initialize the objects.
Point To Remember:
1. The dynamic constructor does not create the memory of the object but it creates the memory block that is accessed by the object.
2. You can also gives arguments in the dynamic constructor you want to declared as shown in Example 2.
Example 1. Dynamic constructor in C++
#include<iostream> using namespace std; class Mania { const char* ptr; public: // default constructor Mania() { // allocating memory at run time ptr = new char[15]; ptr = "Learning Mania"; } void display() { cout << ptr; } }; int main() { Mania obj1; obj1.display(); }
Output:
Learning Mania
Example 2. Dynamic constructor in C++
#include<iostream> using namespace std; class Mania { int num1; int num2; int *ptr; public: // default constructor (here, it is dynamic constructor also) Mania() { num1 = 0; num2 = 0; ptr = new int; } //dynamic constructor with parameters Mania(int x, int y, int z) { num1 = x; num2 = y; ptr = new int; *ptr = z; } void display() { cout << num1 << " " << num2 << " " << *ptr; } }; int main() { Mania obj1; Mania obj2(3, 5, 11); obj1.display(); cout << endl; obj2.display(); }
Output:
0 0 0 3 5 11