~CLASS

closed account (jLNv0pDG)
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 {
// [...]
}
Last edited on
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.

For that class, you wouldn't need a destructor.
Last edited on
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.
Last edited on
Destructors are called when a an object either goes out of scope or is explicitly destroyed via "delete" call on the pointer.

i.e.
1
2
ClassType * blahclass = new ClassType();
delete blahclass


Is similar to this.... but not really.
1
2
ClassType * blahclass = new ClassType();
blahclass->~blahclass();


However when something leaves scope the destructor is called ... note { } scope brackets which can be used to explicitly define scope
1
2
3
{
   ClassType blahclass();
}


Which is similar to this:
1
2
3
4
{
   ClassType blahclass();
}
blahclass.~blahclass();



Topic archived. No new replies allowed.