class Y { public: int i; float f; char a[20]; Y(void); ~Y(void); } Y::Y(void) { i = 0; f = 3.14; a[0] = '\0'; } Y::~Y(void) { cout << "an object of class Y is destroyed!" << endl; }
The destructor method in this example is rather useless, it simply
confirms the destruction. Let us now consider the following block
of code that defines a variable of class Y
type:
{ Y myY; cout << myY.i << " " myY.f << " " << myY.a << endl; }
Immediately after the cout...
statement, the program calls
the destructor of myY
, which prints another line to confirm that
an object of class Y
is destroyed.
Again, the argument for C++ is that this is a cool feature to make sure
myY
has a chance to clean up before it gets deallocated. The
significance of the destructor method becomes very significant as
objects contain pointers to either member objects (not to be confused
with data members) or peer objects.