Dynamic Memory Allocation in C++ Part – 2

Master C++ with Real-time Projects and Kickstart Your Career Start Now!!

Program 1

// Dynamic memory in CPP
#include<iostream>
using namespace std;
class Test
{
    int *ar;
    int n;
    public:
    Test(int limit)   //allocate dynamic memory
    {
         cout<<"\n Dynamic memory allocated: \n";
        ar=new int[limit];
        n=limit;
    }
    void getData()
    {
        cout<<"Enter elements in array";
        for(int i=0;i<n;i++)
        {
            cin>>ar[i];
        }
    }
    void putData()
    {
          for(int i=0;i<n;i++)
        {
             cout<<ar[i]<<endl;
        }
    }
    ~Test()   //deallocate dynamic memory
    {
        cout<<"\n Dynamic memory deallocated: \n";
        delete ar;
    }
};
int main()
{
    system("cls");
     Test T(5);  
     T.getData();
     T.putData();
    return 0;
}

Did we exceed your expectations?
If Yes, share your valuable feedback on Google

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

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