简体   繁体   中英

Should an abstract class' destructor be pure virtual?

I think virtual alone is generally sufficient.

Is there another reason to make it pure virtual than to force derived classes to implement their own destructor? I mean if you allocate something in your class' constructor you should impement your own destructor - if your class is derived or not.

Doesn't count as answer as I already know: If you want your class abstract and it has no pure virtual functions - leave it to the destructor.

Some more uses?

No. If the base class allocates anything, it is it's responsiblity to release it.

Further, if the derived class does not allocte anything, there's no point in forcing them to write a dummy dtor.

If you want your class abstract and it has no pure virtual functions - leave it to the destructor.

Actually, I don't think there's more. All the pure virtual destructor does, is make the whole class abstract. You have to provide the implementation for the pure virtual destructor as well as for a non-pure virtual destructor, the destructors of the derived classes are virtual with virtual destructor alone, etc.

Basically, if a class has already some pure virtual functions, its behaviour would be equivalent with virtual and pure-virtual destructor.

Ideally the language should have a way to assure (implicitly or not) that the destructor is virtual in abstract classes without having to define it or make it pure. But it hasn't.

So the choice is: either make it pure, and have the burden of defining it in each derived class, or make it not, and have the burden of defining it in the abstract class. The later is less work, and also shorter code, so I'd go for it.

If your abstract class is a pure interface, with no data members than you could get along with making the dtor pure virtual. I prefer that myself, since I've seen so many hot-shot programmers forget to make a virtual destructor at all: Even when they write derived classes containing virtual methods. So I would do it purely to minimize maintenance headaches down the road.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM