0

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

16
  • delete[i] array seems invalid, you probably mean delete[] array; Commented May 21, 2020 at 8:37
  • 5
    "I actually want to describe my problem first" But code is more accurate. Commented May 21, 2020 at 8:38
  • Both are wrong. Use standard containers and smart pointers Commented May 21, 2020 at 8:40
  • No, i was not using dynamic array. My array was of fixed size 10. I was talking about deallocating objects :) Commented May 21, 2020 at 8:40
  • I had a brainfart, my answer is incorrect. Commented May 21, 2020 at 8:41

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

5 Comments

If you add the /W4 compiler option it shows "warning C4208: nonstandard extension used: delete [exp] - exp evaluated but ignored". It's a non-conforming extension.
If you disable language extensions with /Za it shows "error C2203: delete operator cannot specify bounds for an array".
@Blastfurnace /Za is soft-deprecated for C++ because it has numerous bugs. Don’t use it, use /permissive- instead.
@KonradRudolph Thanks, that's good to know (I see the note on the MSDN page about it). Unfortunately /permissive- doesn't emit an error for this :(
@Blastfurnace Well that sucks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.