Joshua
Joshua

Reputation: 26722

How to overload a destructor?

How do I overload a destructor?

Upvotes: 17

Views: 26221

Answers (6)

ZenOokami
ZenOokami

Reputation: 210

You don't overload the destructor because you never call it. That's the basic gist of it. (From what we went over in class.)

Upvotes: -1

JaredPar
JaredPar

Reputation: 754565

You can't. There is only one destructor per class in C++.

What you can do is make a private destructor and then have several public methods which call the destructor in new and interesting ways.

class Foo {
  ~Foo() { ... }
public:
  DestroyFoo(int) { ... };
  DestroyFoo(std::string) { ... }
};

Upvotes: 38

Wim ten Brink
Wim ten Brink

Reputation: 26682

Interesting question but the only reason why you'd want to overload a destructor would be because you want to free some resource in one destructor and leave it behind in another one, right?

Basically, you can achieve such behavior from your own destructor by using an additional boolean value which would tell you if a specific resource should be freed or not. This boolean would be set in your constructor and/or one of your other methods and in your destructor you check if it's set. If it's not set, then you'd free the resource. Otherwise, you just leave the resource and probably some other task will free it. (This would make sense when you share resources between multiple objects.)

The reason why you can't overload a destructor is because your code wouldn't have a clue about which destructor it needs to call when you destroy an object. Unless you're calling destructors badly but then you're behaving badly! ;-)

Upvotes: 4

Dima
Dima

Reputation: 39389

Overloading means having several functions with the same name which take different arguments. Like swap(int &a, int &b) and swap(double &a, double &b). A destructor takes no arguments. Overloading it would not make sense.

If you need to do different things when destroying an object depending on certain circumstances, then you just need the appropriate if statements in your destructor to check for those circumstances.

Upvotes: 4

John Dibling
John Dibling

Reputation: 101456

You don't. You can't have 2 destructors in one class.

What are you trying to accomplish?

Upvotes: 0

rlbond
rlbond

Reputation: 67749

You can't! Each class can only have one destructor. How could you have more than one? The destructor is triggered automatically; there's no way the language would know which one to call.

Virtual destructors, however, are another matter.

Upvotes: 1

Related Questions