As CPallini said, you are almost on the right track. There are just a couple of small issues that need to be corrected:
You declared your internal array as
stuff data[];
And that doesn't work here. In C++ there is no such thing as a variable size array. Instead, you should use a pointer to your allocated space, for example:
stuff* pData;
...
safearray (int newSize)
{pData = new int[newSize];}
Then there is an issue in naming conventions. You call the cell type
stuff
, which is kind of misleading.
stuff
would be a good name for a variable that holds your data, but not for the data type itself. For example stuffType would convey that meaning. But most developers use single capital letters or very short capital names to denote their template types, for example "T" or "TYPE".
Your function def_size has the wrong return type. If any it should have return type size_t (or int at best). As this function just
sets the default size, it doesn't need any return type at all. I would declare it as
void def_size ()
But there is yet another error in that function. It assigns a value to the size member variable, but it doesn't allocate the memory for array. Hence, you don't know whether size denotes the size of the array that you have already allocated or the size that should be allocated on the next occasion. There are two ways out of that dilemma:
(a) Always allocate first and then assign the size to your size variable. For exmaple:
void set_default_size()
{allocate (10);}
void allocate (size_t newSize)
{
pData = new int[newSize];
size = newSize;
}
(b) Use two variables, one for the currently allocated size and one for the default size:
private:
size_t m_size; size_t m_defaultSize;
As you see, I prefixed the size names with "m_". That is to help readers of your code to understand that these are member variables, which is not always obvious.
Finally, there is still a problem in the allocate function, above. I separated that code into a function, because it is a little more complex than just using the new keyword. What if the user calls this function several times? The old memory area is lost and with it the contents stored so far. This is called a memory leak. You will be exhausting the heap storage more and more. So you have to check if you have already allocated memory for your array. If yes, and the existing memory is smaller than the requested one, you will have to allocate a new and bigger storage area, then copy the old contents over to that new area and finally dispose of the old storage area by using delete[]. I don't give you the code for that, because this is your homework and a good exersize.