+ 2
C++: practically speaking, when is it useful and have a pure virtual destructor?
Examples welcome
3 Answers
+ 2
A pure virtual destructor is just as useful as a virtual destructor. Only that the class you declare becomes abstract, just like it would become with any other method made pure virtual.
Whats more, the compiler will ask you to provide a default implementation for the destructor.
For more information, see this post: https://stackoverflow.com/questions/1219607/why-do-we-need-a-pure-virtual-destructor-in-c
+ 2
I'd already found that article. But, what is a practical case when a virtual destructor is useful?
+ 1
Paolo De Nictolis
Those help when you store a Derived class object in a pointer to your abstract Base class.
Base* b = new Derived();
delete b;
When you use new, you must pair using delete. delete has no information of the dynamic type of the object, so it will just call the destructor based on the static type (type of the pointer, which is Base) and perform the memory release operations.
This will cause problems if the Derived class's destructor was supposed to perform some extra delete operations for newly allocated memory in the Derived class constructor. So a virtual destructor is required.