+ 2

C++: practically speaking, when is it useful and have a pure virtual destructor?

Examples welcome

3rd Feb 2019, 10:59 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
3 Antworten
+ 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
4th Feb 2019, 2:53 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
I'd already found that article. But, what is a practical case when a virtual destructor is useful?
4th Feb 2019, 7:33 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
+ 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.
4th Feb 2019, 1:21 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar