22.4 Destructors

As well as a constructor, each class has a destructor method with a name like ~SomeClass. (On US keyboards, the '~' symbol is normally on the upper left-hand corner of your keyboard, but in other parts of the world you'll find it somewhere else.) We have no choice about the names of the constructor and destructor methods. For any class SomeClass, the constructor is called SomeClass and the destructor is called ~SomeClass.

When a variable goes out of scope its destructor is automatically called. Thus if your program has a global variable, the variable's destructor is called when your program terminates. If you have a function which has a local variable sctemp in it of type SomeClass, the SomeClass constructor is called when the code execution hits the line where the SomeClass variable is declared, and the SomeClass destructor code for sctemp is called when the execution hits the closing bracket of the function. More precisely, when you hit the closing bracket of a function, the destructors are called for all of the local variables that were declared inside the function. The destructors for local variables are called in the reverse order that the constructors were called.

In the case where you use the new operator to create a pointer to a SomeClass instance, you must explicitly call the delete operator on the pointer to call the destructor and free up the memory.

    Part I: Software Engineering and Computer Games
    Part II: Software Engineering and Computer Games Reference