I want to declare a pointer to an integer array in the header file for my class. I have
private:
int *theName;
and then in the constructor
theName = new int[10];
will this work? Is there another way to do this so you have a pointer to an array?
I thought int *theName created a pointer to an integer not an integer array, if this creates a pointer to an integer array how do you create a pointer to just an integer?
Also in the destructor can I call
delete theName; theName = NULL;
Will that delete theName integer array object and then point theName to null in memory?
Thanks
Four things:
One, yes that is how you make a pointer to an array. Notice that there’s no difference between a pointer to an integer and a pointer to an integer array; you can think of an integer as an array of one element. You can still use
x[0]ifxis a pointer to an integer, and you can still use*xifxis a pointer to an array, and they work the same.Secondly, you have to use
delete[] theName, notdelete theName. Wherever you usenewyou have to usedelete, and wherever you usenew[]you have to usedelete[]. Also, it is unnecessary to settheName = NULLbecause after the destructor is run, you can’t accesstheNameany more anyway.Thirdly, when you write a class that manages resources, you need to write a copy constructor, move constructor, copy assignment operator and move assignment operator.
Fourthly, unless you are just doing this as a didactic exercise, you should really use
std::vector. It has many advantages and no real disadvantages. And you don’t even have to write the four other constructors if you usevector.