delete []apple;
wouldn't compile, but you obviously have a runtime error, so you must have delete []array;
. First of all, this is correct!
Assuming your class is next to trivial, the reason for the error could be that two of your NameClass
objects have an array
pointer that points to the same array. This can happen if your class does not have a user-defined copy constructor and/or assignment operator, in which case the compiler will generate one for you. If you then do something like this
NameClass n1;
NameClass n2 = n1;
or
NameClass n1;
NameClass n2;
n2 = n1;
in your code, the compiler will just assign all the members (including the array
pointer) to each other, making array
point to the same piece of memory in both objects (and, in the latter case, cause a memory leak for the memory initially allocated in the constructor of n2
). What you need to do is to define the copy constructor and assignment operator such that they make a copy of the array pointed to by array
. Because the things you do in the destructor, in the copy constructor and in the copy assignment operator (and in the constructor, but that is obvious) have to be compatible to each other, this is called the Rule of Three.