CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Dynamically allocating memory for arrays

If we use new[] to allocate arrays, they can have variable size

#include <iostream>

    int numItems;
    cout << "how many items?";

    cin >> numItems;
    int *arr = new int[numItems];

We then de-allocate arrays with delete[] :

    delete[] arr;

Allocating class instances

new can also be used to allocate a class instance The appropriate constructor will be invoked

#include <iostream>

class Point {
public:
    int x, y;
    Point(void) {
	x = 0; y = 0;
	cout << "default constructor" << endl;
    }
};

int main(void) {
    Point *p = new Point;
    ....
    delete p;
}

The appropriate constructor will be invoked.

#include <iostream>

class Point {
public:
    int x, y;
    Point(int nx, int ny) {
	x = ny; x = ny; cout << "2-arg constructor" << endl;
    }
};

int main(void) {
    Point *p = new Point(2, 4);

    delete p;
}

 


CITS2002 Systems Programming, Lecture 23, p11, 17th October 2023.