Destructor methods in C++ - a primer
Archive - Originally posted on "The Horse's Mouth" - 2011-11-05 07:24:57 - Graham EllisConstructor methods - named pieces of code which create a new object - are key to any object oriented program / programming. Without objects, an object oriented program isn't really an object oriented program, and they need to be created somehow. But what happens at the other end of the life cycle?
When a program completes, it's flushed from memory and that means that the obejcts that have been used are 'lost'. In most cases, by this time they have fulfilled theie purpose and can simply be allowed to disappear - but that's not always the case; work in progress may be held within an object which needs saving to permanent storage, for example. And what if you want to get rid of an object earlier - after it's fulfilled its purpose, so that you can reuse the memory it has occupied.
In order to meet these extra requirements, object oriented languages support destructor methods. How they're implemented, and how and when they're run differ from language to language ... I'm going to use C++ as am example, using an example [here] which I wrote during yesterday's C++ for C Programmers course.
How is a constructor declared and defined?
It's declared as a method with the same name as the name of the class with a leading tilde, and without any parameters:
class Book {
public:
Book(int);
~Book();
etc
(example also shows a constructor with a single parameter)
What is does is defined as a method in the usual way. Here's an example of that destructor's code with - for learning purposes - a message output to tell you that it's being run:
Book::~Book() {cout << "Gone " << npages <
When do destructors in C++ run?
1. For objects created on the stack - for example
Book pottering(156);
the destructor is run when the variable goes out of scope - i.e. at the end of execution of the block in which it is defined. So if it's in main that will be when the program terminates, and if it's in another method that will be much earlier and indeed objects may be lost and recreated many times over in a functions that's called repeatedly
2. For objects created on the heap - for example
Book * inbed = new Book(99);
you'll call the destructor directly when you're done with them - e.g.
inbed->~Book();
and failure to do so can in some circumstances lead to an application which grows, grabbing more and more memory. For a short-run program that may not be an issue, but for a server process that can be whet'a often described as a "memory leak". Particular care need to be taken of apparently inocuous code lines such as
inbed = new Book(45);
which loose the memory held by (any) previous Book object creation unless a second copy of the pointer has been stored so that you can retain access. This is rather different to other OO Languages which retain link counts for objects and automatically schedule the destructor to be run when the link count is reduced to 0