Write a programme to demonstrate the Dynamic Memory Allocation with some real-time
example. Also, mention the possible ways of intializing and deallocating memory from dynamically
created objects of the class
#include <iostream>
using namespace std;
class Numbers
{
int* p;
int n;
public:
//Default constructor p=NULL
Numbers():p(NULL),n(0){}
//Parametrized constructor
Numbers(int *_p,int _n) : n(_n)
{
p = new int[n]; //dynamically allocate memory
for (int i = 0; i < n; i++)//make copy data
{
p[i] = _p[i];
}
}
void Display()
{
cout << "\nClass Numbers: ";
for (int i = 0; i < n; i++)//make copy data
{
cout<<p[i]<<" ";
}
}
//Deallocate memory in destructor
~Numbers()
{
delete[]p;
cout << "\nNumbers destructor";
}
};
int main()
{
int l;
cout << "Please, enter a size of array: ";
cin >> l;
int *p = new int[l];
cout << "Please, fill array: ";
for (int i = 0; i < l; i++)
{
cin >> p[i];
}
cout << "You are entered: ";
for (int i = 0; i < l; i++)
{
cout<< p[i]<<" ";
}
Numbers a(p, l);
a.Display();
delete[]p;
}
Comments
Leave a comment