SoundChaos
SoundChaos

Reputation: 307

VS 2015 c++ compile issue

I have a code snipped I've been using for a while to create dynamic arrays, and it suddenly stopped working.

This is meant to create a dynamic array without the use of vector in c++ console applications. even all my older programs that have worked fine in the past no longer compile while its included though.

int main()
{
    int n = 5;

    AllocateArray newArray(n);

    int *myArray = newArray.create();

    delete[] myArray;

    return 0;
}

class AllocateArray {
private:
    int *newArray;
    int size;
public:
    AllocateArray(int);
    int* create() { return (newArray = new int[size]); }
    ~AllocateArray() {
        delete newArray;
    }
};

AllocateArray::AllocateArray(int n)
{
    size = n;
}

with this in the header

int* allocateArray(int n);

This is my error log, can anyone help find whats happening?

Severity    Code    Description
Error       C2065   'AllocateArray': undeclared identifier
Error       C2146   syntax error: missing ';' before identifier 'newArray'  
Error       C3861   'newArray': identifier not found
Error       C2065   'newArray': undeclared identifier   
Error       C2228   left of '.create' must have class/struct/union

Upvotes: 0

Views: 481

Answers (1)

bku_drytt
bku_drytt

Reputation: 3249

Move your declaration of AllocateArray before main().

As user @JoachimPileborg explains:

C++ needs the symbols you use to be declared (and sometimes defined) before they are used.

class AllocateArray {
private:
    int *newArray;
    int size;
public:
    AllocateArray(int);
    int* create() { return (newArray = new int[size]); }
    ~AllocateArray() {
        delete[] newArray; // changed to 'delete[]' from 'delete'
    }
};

int main()
{
    int n = 5;

    AllocateArray newArray(n);

    int *myArray = newArray.create();

    //delete[] myArray; // error: delete is called by AllocateArray's destructor.

    return 0;
}

AllocateArray::AllocateArray(int n)
{
    size = n;
}

Warning

You are deleting the same pointer P twice. Once in AllocateArray's destructor and once in main(). P is returned by your create() function to myArray in main(). Then you delete it, but at the end of main(), AllocateArray's destructor is called and it tries to delete P again.

Notes

You should check out the RAII idiom if you plan on allocating arrays by yourself. However, you should consider using std::vector<T> instead, as it manages memory for you (and provides a very useful range of functionalities).

Upvotes: 1

Related Questions