When should virtual destructors be used in C++ and what happens if they are not declared?
Hello everyone! I've just started learning C++ and I can't understand one thing. Look:\n\nI have a base class `Base` and a derived class `Derived`. In `Derived`, I allocate memory on the heap. When I create an object through a pointer to the base class and then delete it using `delete`, only the destructor of `Base` is called, but the destructor of `Derived` is not. This leads to a memory leak because the memory allocated in the derived class is not freed.\n\nI know that I need to add `virtual` before the destructor in the base class, and then everything works. But why does this happen? After all, I explicitly wrote code that should call the destructor of the derived class? Or am I confusing something?\n\nHere is an example of code that does not work for me (or rather, it works, but with a leak):\n\n```cpp\nclass Base {\npublic:\n ~Base() { std::cout
No answers yet.
Log in to leave an answer
Blogs