c++ – C ++ Destroy objects from an array

Question:

Hello, I have a couple of questions

Let's say I have this code:

class alumno
{
    private:
        string nombres;
        char telefono[12];
        int nivel;
    public:
        alumno();
        ~alumno();
}

and then in the main I declare

alumno estudiante[10];

My doubts are:

  • How do I call the destructor for a single object?
  • How do I destroy the whole arrangement?
  • If I delete an object, is the data blank? or does the object box disappear? (So ​​if the size of the arrangement is 10, will it go down to 9?)

Answer:

1. What do I call the destructor for a single object?

Inside an array, you can make estudiante[3].~alumno( );

2. How do I destroy the whole arrangement?

As you have declared, the array is destroyed when exiting the function, automatically. Before said destruction , the destructors of the objects contained in the array are invoked one by one.

If you want to be able to destroy it whenever you want, you have to use dynamic memory:

alumno *estudiante = new alumno[10];
...
delete[] alumno;

If you use this last formula, dynamic arrays, remember that it is your responsibility to destroy them by doing the delete[] . The compiler totally ignores them. That is, they are not destroyed or released when exiting the function.

3. If I delete an object, is the data blank? or does the object box disappear? (So ​​if the size of the arrangement is 10, will it go down to 9?)

If the instances are within an array , neither the array nor the data changes. Everything remains as it is when the destructor of the involved class ends.

If the destroyer does nothing, the memory remains as it was. Of course, the number of elements in the array does not change .

Think that, from the compiler's point of view, an array is nothing more than a block of memory . Once assigned , it does not change size (unless we change it explicitly).

Be careful what you do. Logically, if you first call an object's destructor, and then delete the entire array, the destructor will be called again . It's up to you to check the logic of your program.

Scroll to Top