What is a dynamic constructor in C++?

In this blog post, you will learn the C++ dynamic constructor with the help of programming example code. I believe you are already familiar with C++ constructors. If you are new and don’t know anything about the constructor,  then it is my advice to read the constructors and their uses in C++ programming.

 

Dynamic constructor in C++:

In C++, class constructors are special member functions use to initialize objects of their class type. The class constructor invokes automatically whenever we create new objects of that class.

Now you know what a constructor is, but still, the question is pending what is a dynamic constructor.

So the dynamic constructor is a type of constructor which allocates memory dynamically to the objects using dynamic memory allocator (new). By using this, we can dynamically initialize the objects (allocate the memory to the objects at the run time).

 

Example of Dynamic constructor:

The following example shows how a dynamic constructor allocates memory at run time. Below example code has two constructors one is default and the second one is parameterized.

#include <iostream>
using namespace std;

class DynamicCons
{
    int * m_ptr;
public:
    DynamicCons()
    {
        m_ptr = new int;
        *m_ptr = 27;
    }
    DynamicCons(int data)
    {
        m_ptr = new int;
        *m_ptr = data;
    }
    void display()
    {
        cout<< *m_ptr <<endl;
    }
    ~DynamicCons()
    {
        delete m_ptr;
    }
};

int main()
{
    DynamicCons obj1, obj2(6);

    cout<<"The value of object obj1's m_ptr is: ";
    obj1.display();

    cout<<"\nThe value of object 0bj2's m_ptr is: ";
    obj2.display();

    return 0;
}

Output:

dynamic constructor in Cpp Aticleworld

 

Recommended Page for you:

Leave a Reply

Your email address will not be published. Required fields are marked *