I'm just trying to get a handle on destructors at the moment. Are destructors only used when a class dynamically allocates memory with new or pointers?
For the following BASIC class, what should the destructor look like?
1 2 3 4 5 6 7 8 9 10 11
class BASIC {
private:
int i;
public:
BASIC(int n);
~BASIC();
};
BASIC::~BASIC {
// [...]
}
Usually. There might be times when you use the destructor to perform other tasks, like maybe print a message or close a file or whatever, but the most common use is when you have dynamic memory.
Which is to say that if a destructor is not explicitly defined, the compiler will generate one for you. It is still there and executed upon object destruction. Objects are destroyed when a pointer to them is deleted or, for local objects, when they go out of scope1.
The need to explicitly provide a destructor usually comes from a class that contains something other than just plain old data (POD) members. Examples include dynamically allocated members (usually pointers), and any other resource that the object acquires that will need released.
Another need to provide a destructor may be to declare it virtual. If the class will be used as a base class, providing a virtual destructor prevents a base-poniter from only partially destroying a derived object.
--- 1There are rare instances when a destructor is called explicitly but that goes beyond the scope of this thread.