Programming with Passion

Make the best out of everything.

Monday, 21 March 2016

C++ Memory Management

C++ Memory Management

Object-oriented approach to handle above program in C++.
    
#include <iostream>
using namespace std;

class Test {
private:
    int n;
    float *ptr;
public:
    
    Test() {
        cout << "Enter total number of students: ";
        cin >> n;
        
        ptr = new float[n];
        
        cout << "Enter GPA of students." <<endl;
        for (int i = 0; i < n; ++i) {
            cout << "Student" << i+1 << ": ";
            cin >> *(ptr + i);
        }
    }
    
    ~Test() {
        delete[] ptr;
    }

    void Display() {
        cout << "\nDisplaying GPA of students." << endl;
        for (int i = 0; i < n; ++i) {
            cout << "Student" << i+1 << " :" << *(ptr + i) << endl;
        }
    }
    
};
int main() {
    Test s;
    s.Display();
    return 0;
}
The output of this program is same as above program. When the object s is created, the constructor is called which allocates the memory for n floating-point data.
When the object is destroyed, that is, object goes out of scope then, destructor is automatically called.
    ~Test() {
        delete[] ptr;
    }
This destructor executes delete[] ptr; and returns memory to the operating system.

No comments:

Post a Comment