on Leave a Comment

C++ Dynamic Constructor

We can initialize an object through constructor. We know that constructor is automatically called, when an object create. A dynamic constructor allocates dynamically created memory block to an object. A dynamic constructor is same as normal constructor, but the only difference is that, it allocates dynamically created memory to an object. Syntax of dynamic constructor is same as normal constructor.

Assume that, a class has a pointer and we want to initialize this pointer through constructor by passing appropriate arguments to that constructor. When an object of that class is created, constructor is automatically called, and this constructor dynamically creates a memory block and allocates memory block to that pointer. This type of constructor is called dynamic constructor. 

C++ Program for Dynamic Constructor

#include<iostream>
using namespace std;
class Dynamic_Constructor
{
private:
    int x, y;
    float *z;
public:
    Dynamic_Constructor() //Constructor 1
    {
        x = 0;
        y = 0;
        z = new float;
        *z =0;
    }
    Dynamic_Constructor(int a, int b, float c) //Constructor 2
    {
        x =a;
        y = b;
        z = new float;
        *z = c;
    }
    void displayData()
    {
        cout<<"Value of x is "<<x;
        cout<<"\nValue of y is "<<y;
        cout<<"\nAddress stored in pointer (z): "<<z;
        cout<<"\nValue at the address stored in pointer (z) is "<<*z<<endl;
    }
};
int main()
{
    Dynamic_Constructor d1;
    cout<<"Constructor 1 is called\n\n";
    d1.displayData();
    Dynamic_Constructor d2(1, 2, 3.0);
    cout<<"\nConstructor 2 is called\n\n";
    d2.displayData();
    return 0;
}

OUTPUT:

Constructor 1 is called

Value of x is 0
Value of y is 0
Address stored in pointer (z): 0x5e56d8
Value at the address stored in pointer (z) is 0

Constructor 2 is called

Value of x is 1
Value of y is 2
Address stored in pointer (z): 0x5e5718
Value at the address stored in pointer (z) is 3

0 comments:

Post a Comment