
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When to Use Virtual Destructors in C++
Scott Meyers in Effective C++ says −
If a class has any virtual function, it should have a virtual destructor, and that classes not designed to be base classes or not designed to be used polymorphically should not declare virtual destructors.
So you should declare destructors virtual in polymorphic base classes. This is because if you create an object of base class using a derived constructor −
Base *b = new Derived(); // use b delete b;
If Base's destructor is not virtual then delete b has undefined behavior in this case. The call to the destructor will be resolved like any non-virtual code. So the destructor of the base class will be called but not the one of the derived class, this will result in a resources leak.
Advertisements