0

I'm trying to learn more about C++ ,int this code I'm allocating an array of A's (5 in this case), what I understand that 5 A's will be allocated ...so the compiler will call 5 times the constructer , but in case of deleting that array it calls the destructor one time only ,so my question is why does it call the destructor one time only when it has 5 A's , shouldn't he call the destructor 5 times??

I have this code :

#include <iostream>
using namespace std;

class A {
public:
    A() { std::cout << "IM in C'tor" << std::endl; };
    ~A() { std::cout << "IM in De'tor" << std::endl; }
};


int main()

{
    A* a = new A[5];
    delete a;  // ingone the errors,the important thing is calling the 
                 C'tor and D'tor` 
    return 0;
}
sallyaaa
  • 25
  • 5

1 Answers1

1

You need to use delete[] a to delete an array of things allocated with new[]. If you do that, you'll see the correct output:

IM in C'tor
IM in C'tor
IM in C'tor
IM in C'tor
IM in C'tor
IM in De'tor
IM in De'tor
IM in De'tor
IM in De'tor
IM in De'tor
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953