First of all, you have no copy constructor (or assignment operator). This will be a problem in this case:
void foo(Array a) {
//...
}
int main() {
Array a(10);
foo(a);
//a is still around, but the pointer has been destroyed.
}
Since there will be two instances of Array using the same pointer. Once one of them goes out of scope, the destructor is called, so the delete[] happens. However, there is still another instance of Array with that same pointer, which has no way to know that delete happened. This is solved by following the "Rule of Three" See "Dynamically allocating an array of objects for a simple example.
In second place, you have a member called array
. What's it for? It's never used so why have it?
In third place, some members are protected
. Why? Does this mean you plan to have Array be inherited? In that case, you might want to make the destructor virtual. But I'd advise against inheritance, as it would feel counter-intuitive.
The implementation of get
and set
use unnecessary pointer arithmetic.
Just do:
return arrayPointer[index];
This does the same thing and it's much cleaner to look at.
In fourth place, you do a check on the values of index for set
, but not for get
. Why not?
In fifth place, index is a signed integer. You may want to consider using size_t
instead. It will also make the < 0
check redundant.
In sixth place, usage of get
and set
feels unnatural. You may want to look at operator overloading.
In seventh place, I would not use cout
for the error message. Use assert()
, cerr
or an exception, depending on what your exact needs are.
In eighth place, you call it Array
but you only allow integers to be stored. I'd either name it IntArray
or make it a template to allow other types to be stored.
As for "Putting your class in another file", that might be a good idea, especially if you want Array
to be used in multiple files. Put it in a header file.
Also, why create your own Array
class? Is this for learning purposes? If not, you may want to use std::array
or std::vector
instead.