next up previous
Next: How do I put Up: class and struct Previous: What is a destructor?


How do I free the memory allocated to a class?

The method called when the memory occupied by a class is freed is called the destructor. With derived classes, destructor should always be virtual. If a class is destroyed through a base class pointer whose destructor isn't virtual, the result is undefined (only part of the destructors will be called).
struct A
{
  A() {}
  virtual ~A() {}
};

struct B: public A
{
  B() {}
  ~B() {}
};

void	function()
{
  B *b = new B();
  A *a = b;

  delete a; // calls ~A and ~B. If ~A wasn't virtual, only ~A would be called.
}



Alexis Angelidis (PhD) 2005-01-11