Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 822
spc-mrn Avatar asked Aug 17 '10 13:08

spc-mrn


People also ask

Does pure abstract class need virtual destructor?

Pure virtual destructors in C++To work correctly, classes with virtual methods must also have virtual destructors. Interestingly, virtual destructors can be declared pure, which can be useful in some cases. Imagine you have a base class you want to make abstract.

Can a destructor be pure virtual?

Yes, it is possible to have a pure virtual destructor. Pure virtual destructors are legal in standard C++ and one of the most important things to remember is that if a class contains a pure virtual destructor, it must provide a function body for the pure virtual destructor.

Can we have destructor in abstract class?

An abstract class can have constructors or destructors. An abstract class cannot be inherited from by structures. An abstract class cannot support multiple inheritance.

Should a destructor be virtual?

In particular, here's when you need to make your destructor virtual: if someone will derive from your class, and if someone will say new Derived, where Derived is derived from your class, and if someone will say delete p, where the actual object's type is Derived but the pointer p's type is your class.


2 Answers

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.

like image 174
jpalecek Avatar answered Sep 28 '22 08:09

jpalecek


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.

like image 25
James Curran Avatar answered Sep 28 '22 07:09

James Curran