skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
cpp-virtual-destructor
This page is read only. You can view the source, but not change it.
# C++ virtual destructor **[Virtual destructor](https://en.cppreference.com/w/cpp/language/virtual)** is required in base classes meant for polymorphic use. When deleting a derived object through a base pointer, a non-virtual destructor calls only the base destructor, leaving derived cleanup code unrun and causing resource leaks. Always declare destructors virtual in base classes, or make the class final if inheritance isn't intended. ## Example This example shows how a virtual destructor ensures derived cleanup runs correctly. ```cpp // compile: g++ -o vdtor vdtor.cpp // run: ./vdtor // description: virtual destructor ensures derived cleanup in polymorphic code #include <iostream> class Base { public: virtual ~Base() { std::cout << "Base destroyed\n"; } }; class Derived : public Base { private: int* data = new int[1000]; public: ~Derived() { delete[] data; std::cout << "Derived destroyed\n"; } }; int main() { { Base* ptr = new Derived(); delete ptr; // virtual destructor calls Derived::~Derived() } return 0; } ```
Page Tools
Show pagesource
Backlinks
Back to top