-1

I am confused. Do you have to do delete s[] at the end of the code?

What is the correct way of assigning derived class objects to an array (fixed size) of type base class?

int main () {

    Shape *s[2];
    s[0] = new Circle(...);
    s[1] = new Rectangle(...);
    // etc

    delete s[] // Do you have to delete ?
}
jkdev
  • 11,360
  • 15
  • 54
  • 77
J.S
  • 1
  • 1
  • 3
  • `delete s[]` is not a valid syntax. It would not compile. So of course you should not add this to your code. – Igor Tandetnik Aug 11 '19 at 02:00
  • There are two invocations of `new` in this code, so there should be two invocations of `delete`. Since you stored pointers to allocated memory in `s[0]` and `s[1]`, you should be deleting `s[0]` and `s[1]`, as in `delete s[0]; delete s[1];`. Or something like `for (int i = 0; i < 2; ++i) delete s[i];` Better still, use smart pointers (e.g. `std::unique_ptr`) in place of raw pointers, and possibly standard containers (e.g. `std::vector`) in place of arrays. – Igor Tandetnik Aug 11 '19 at 02:04
  • Possible duplicate of [Object destruction in C++](https://stackoverflow.com/questions/6403055/object-destruction-in-c) – DCTID Aug 11 '19 at 02:10
  • @IgorTandetnik Thank you. So if have `Shape *s[10]` but only have s[0] and s[1], when deleting using for loop, do i loop until 10 like . `for (int i = 0; i < 10; ++i) delete s[i];` – J.S Aug 11 '19 at 02:16

2 Answers2

1

The behaviour depends on where you allocate the actual memory. If you allocate the array on the stack you shouldn't free the memory for the array itself, but you still have to iterate over all pointers to free the memory:

    Shape* s[2];
    s[0] = new Circle;
    s[1] = new Rectangle;
    for (int i = 0; i < 2; ++i)
    {
        delete s[i];
    }

Or if you really want to allocate memory in the heap for some reasons, you can just create an array of pointers on the heap, so don't forget to release the memory of the array itself:

    Shape **s = new Shape*[2];
    s[0] = new Circle;
    s[1] = new Rectangle;
    for (int i = 0; i < 2; ++i)
    {
        delete s[i];
    }
    delete[] s;
IgnatiusPo
  • 31
  • 7
0

Typically you need to manually delete, but if it is in int main, you don't need to because the OS will automatically release all memory you allocated after the program completes.

However that is only true if you allocated memory using the new Shape[n] syntax. Using your syntax, you don't need to release an array.

delete[] won't release the underlying pointers, just release the array of pointers. You need to loop through and manually delete the contents as well.

SOFe
  • 7,867
  • 4
  • 33
  • 61
  • This is, in my opinion, a dangerous habit: not calling `delete` on any object created with `new` means that the object's destructor will not be called, see, eg. https://stackoverflow.com/questions/677812/is-there-a-reason-to-call-delete-in-c-when-a-program-is-exiting-anyway. – rainer Aug 11 '19 at 04:59