6.3 Nested destructors

If a class include data members that are also objects of classes, the destructors of the data members are invoked after the destructor of the containing object. This means during the destruction of the containing object, it can continue to refer to the content of the data members.

This can be illustrated by the following program:

#include <iostream>
using namespace std;

class Component
{
  public:
    ~Component(void);
};

class Whole
{
    Component c1, c2;
  public:
    ~Whole(void);
};

Component::~Component(void)
{
  cout << "A Component is destroyed" << endl;
}

Whole::~Whole(void)
{
  cout << "A Whole is destroyed" << endl;
}

int main(void)
{
  Whole w;

  return 0;
}



Copyright © 2006-09-26 by Tak Auyeung