tags:

views:

540

answers:

6

How do I overload a destructor?

+14  A: 

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) { ... }
};
JaredPar
wouldn't that kill RAII?
Qberticus
@Qberticus, yes it would in some ways. There's still nothing stopping the OP from creating an additional class which has simple RAII and destroys Foo in an interesting way. Without more info from the OP I can't tell. I'm hoping the OP considered this and is taking that into account in their solution.
JaredPar
Um that's private *destructor* ...
Steve Fallows
@Neil, thanks, updated.
JaredPar
+1  A: 

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.

rlbond
A: 

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

What are you trying to accomplish?

John Dibling
A: 

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.

Dima
+1  A: 

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! ;-)

Workshop Alex