I have a class:
class Rectangle {
int width;
int height;
public:
Rectangle(int w, int h) {
width = w;
height = h;
cout << "Constructing " << width << " by " << height << " rectangle.\n";
}
~Rectangle() {
cout << "Destructing " << width << " by " << height << " rectangle.\n";
}
int area() {
return width * height;
}
};
int main()
{
Rectangle *p;
try {
p = new Rectangle(10, 8);
} catch (bad_alloc xa) {
cout << "Allocation Failure\n";
return 1;
}
cout << "Area is " << p->area();
delete p;
return 0;
}
This is a quite simple C++ sample. I compiled in Linux g++ and run it.
Suddenly I found the delete p did not call ~Rectangle() …
I should see string like "Destructing " << width << " by " << height << " rectangle."
but I did not ….
but why?
Deleting an object should call that object’s destructor, shouldn’t it?
You haven’t ended the line, so the line was not output. Add
<< endlto your printing.