Dynamic Constructor in C++ with Examples

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 << endl;
 }
};

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 << endl;
 }
};

int main()
{
 mania obj1;
 mania obj2(3, 5, 11);
 
 obj1.display();
 obj2.display();
}


/* OUTPUT

0 0 0
3 5 11

*/



<< Previous                                                                                      Next >>
Previous
Next Post »