Reputation: 1
I actually want to describe my problem first. In my code I've a base class with name Employee then I've 4 more classes. I wanted to make my class abstract (basically i was using polymorphism concept). I made a pointer array with type of base class and add objects in it(unnamed objects on heap). Now i wanted to deallocate objects. I used delete[i] array
and delete array[i]
both were working(one at a time). Can someone please explain the difference between both of them? Why both were working if delete[i]
is wrong?
I was using delete[i] array
or delete array[i]
with for loop.
main
is like:
Employee *arr[10];
arr[0] =new SalariedEmployee ("first name","last name","number",200);
now i want to delete this object
Upvotes: 0
Views: 72
Reputation: 11340
delete[i] array;
is wrong in standard C++. But it acutally compiles on msvc (demo). It's a compiler specific extension (thanks to Blastfurnace for pointing this out).
The correct version is
delete array[i];
to destroy an object that was allocated on the heap and free the corresponding memory.
However, manual memory management can become quite hard sometimes. So the solution in modern C++ would be something like
std::array<std::uniqe_ptr<Employee>, 10> array;
for a fixed size array with pointers to Employee
's.
Upvotes: 3