Consider the following example:
#include <iostream>
class Base
{
public:
Base() { std::wcout << L"Base cons" << std::endl; }
~Base() { std::wcout << L"Base des" << std::endl; }
};
class Derived : public Base
{
public:
Derived() { std::wcout << L"Derived cons" << std::endl; }
~Derived() { std::wcout << L"Derived des" << std::endl; }
};
int main()
{
Base * derived = new Derived;
std::wcout << L"Deleting..." << std::endl;
delete derived; // Base::~Base() is not virtual so only Base::~Base() is called
return 0;
}
// Ouput
// Base cons
// Derived cons
// Deleting...
// Base des
Since Base::~Base() is not virtual, when the object "derived" is deleted, only Base::~Base() will be executed. Wouldn't it be a memory leak if we don't call Derived::~Derived() too? Of course this is easily remedied by marking the Base::~Base() deconstructor as virtual, but what is a scenario that one would want to destruct the base derived class and not the derived class?
(It's my understanding that once the base class destructor is invoked, the derived object is no longer in a usable state)
I realize C++ is designed for efficiency -- "only pay for what you need" -- so I'm really just looking to understand why declaring a derived class does NOT require a virtual base class deconstructor (to avoid the inherent memory leak of not cleaning up the derived class)
Thanks for your insights in advance.