Understanding destructors
Recall how conveniently a class constructor provides us with a way to initialize a newly instantiated object? Rather than having to remember to call an Initialize()
method for each instance of a given type, the constructor allows initialization automatically. The signature used in construction helps specify which of a series of constructors should be used.
What about object clean-up? Many classes contain dynamically allocated data members, which are often allocated in a constructor. Shouldn’t the memory comprising these data members be released when the programmer is done with an instance? Certainly. We have written a CleanUp()
member function for several of our example programs. And we have remembered to call CleanUp()
. Conveniently, similar to a constructor, C++ has an automatically built-in feature to serve as a clean-up function. This function is known as the destructor.
Let’s look at the destructor to understand its proper usage.
...