I had the following code, on which I tried doing a dynamic_cast:
struct Base {
Base() {}
~Base() {}
};
struct Derived: public Base {
Derived() {}
~Derived() {}
};
struct AnotherClass: public Base {
AnotherClass() {}
~AnotherClass() {}
};
int main() {
Derived* d = new Derived();
Base* base = d;
AnotherClass* ac = dynamic_cast<AnotherClass*> (base);
}
This led to the following error:
the operand of a runtime
dynamic_castmust have a polymorphic class type.
Making the Base class destructor virtual fixes this.
But why does the destructor need to be virtual here for base to be considered to have a polymorphic class type?
Since AnotherClass and Derived inherit from Base, aren't they already considered polymorphic types?
You don't really need a virtual destructor for
dynamic_cast. The only thing needed is at least one virtual method in the Base class, to allow the compiler to generatetype_infofor the class hierarchy typeid.But, you actually do need the virtual destructor, because without it you cannot properly release the resources held by a derived class when using a pointer to the Base class. In other words:
Base* b = new Derived(); delete b;is Undefined Behavior without a virtual destructor.