C++ Initializing a Global Array

If you actually want an array and not a vector, and you want that array dynamically sized at runtime, you would need to create it on the heap (storing it in a pointer), and free it when you’re done.

Coming from Java you need to understand that there’s no garbage collection in C++ – anything you new (create on the heap) in an object you will want to clean up in the destructor with delete.

class foo
{
    private:
    int *array;

    public:
    foo() { array = NULL; };
    ~foo()
    {
        if (array != NULL)
            delete [] array;
    }

    void createArray()
    {
        array = new int[5];
    }

};

More info at: http://www.cplusplus.com/doc/tutorial/dynamic/

Leave a Comment

tech