Answer to Question #330819 in C++ for Harsh

Question #330819

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

1
Expert's answer
2022-04-20T12:40:44-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS