C++ Concept Map

Destructor functions

The destructor function is a special function that a class uses to recover the space allocated to an instance of that class. The destructor is called whenever an object goes out of scope. Every class has a destructor function even if none is defined. In this case the equivalent definition is

~X() {}
Where X is the name of the class. Note there is no return type (just like the constructor functions), there are no parameters and the tilde (~) must be present. Destructors should be public to be of any use.

There can only be one destructor for a class, but its body can be defined in any chosen fashion. Typically the destructor can use delete on pointers initialized with new to ensure that dangling pointers are not left.

For example, in the class below, the constructor creates a data member with new, and the destructor destroys it.

class Y { ... };

class X {
private:
   Y* mem1;
public:
      X() { mem1 = new Y; }
     ~X() { delete mem1; }
};
Where a data member is of a (non-pointer) class type, or when a class is derived, its destructor will be called when the containing or deriving class destructor is called. So, in class A below, there is a member of type B whose destructor will be called when an object of type A is destroyed. Since B is derived from C, the destructor for C is called when B's destructor is called.
class C { ... };

class B : public C {
...
public:
     ~B() {} // when this is called, ~C() is called first
};

class A {
...
   B b;
public:
     ~A() {} // when this is called, ~B() is called first for member b;
...
};


Please mail any corrections and/or suggestions to Roger Hartley at
rth@cs.nmsu.edu

Copyright © 2003 Roger Hartley