I’ve had some second thoughts on multiple virtual destructors, esp. after reading reading http://blogs.msdn.com/b/oldnewthing/archive/2004/05/07/127826.aspx .
Suppose I have
class Base
{
public:
Base();
virtual ~Base();
private:
Logger* _logger;
};
//and
class Derived : public Base{
public:
Derived();
virtual ~Derived();
private:
Logger* _logger;
};
in the cpp files, in each destructor I am deleting the respective _logger pointers
Base::~Base(){ //base.cpp
delete _logger;
}
Derived::~Derived(){ //derived.cpp
delete _logger;
}
will this work as I intended, without memory leaks?
First off, if you make the base class destructor
virtual, all derived classes will automatically get avirtualdestructor if you declare them asvirtualor not. This is generally true for matching signatures: if a base class has avirtualfunction with the same signature as a function in a derived class, the function in the derived class is anoverrideand isvirtual(although in C++ 2011 you can prevent further overriding using thefinalkeyword in which case another override would create an error).That said, destructors are special: when you make a destructor
virtualit will still be called even if there is another overriding destructor! The only impact of a destructor beingvirtualis what happens if youdeletean object using a pointer to a base class when the object actually happens to be of a derived type: If the destructor isn’tvirtualyou get undefined behavior while the Right Thing happens if the destructor isvirtual. For example:The reason destructors are not
virtualby default is simply that this would mean that object size is always increased by a word size which is unacceptable in general.