Destructors
What bad can happen if one doesn't define a destructor in the base class as virtual
?
Just virtual destructor
#include <iostream>
class ProtectedDestructor {
public:
ProtectedDestructor() {
std::cout << "[ProtectedDestructor] constructor" << std::endl;
}
virtual ~ProtectedDestructor() {
std::cout << "[ProtectedDestructor] destructor" << std::endl;
}
};
class PleaseLetMeDelete : public ProtectedDestructor {
public:
PleaseLetMeDelete() {
std::cout << "[PleaseLetMeDelete] constructor" << std::endl;
}
~PleaseLetMeDelete() {
std::cout << "[PleaseLetMeDelete] destructor" << std::endl;
}
};
int main(int argc, char const *argv[])
{
ProtectedDestructor* obj = new PleaseLetMeDelete();
delete dynamic_cast<PleaseLetMeDelete*>(obj);
// delete obj;
return 0;
}
Virtual and Protected destructor
#include <iostream>
class ProtectedDestructor {
public:
ProtectedDestructor() {
std::cout << "[ProtectedDestructor] constructor" << std::endl;
}
protected:
virtual ~ProtectedDestructor() {
std::cout << "[ProtectedDestructor] destructor" << std::endl;
}
};
int main(int argc, char const *argv[])
{
const ProtectedDestructor* obj = new ProtectedDestructor();
// delete dynamic_cast<PleaseLetMeDelete*>(obj);
// delete obj; // error: destructor is inaccessible
return 0;
}