1

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_cast must 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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Does this answer your question? [When to use virtual destructors?](https://stackoverflow.com/questions/461203/when-to-use-virtual-destructors) – Ahmed AEK Mar 12 '23 at 17:57
  • Not a good dup': no answers mention `dynamic_cast`. – YSC Mar 12 '23 at 17:59
  • "_aren't they already considered polymorphic types?_": "_polymorphic class type_" in this context is a technical C++ term defined in the ISO C++ standard (see already posted answer for definition). It doesn't have (exactly) the same meaning as "_polymorphic_" does in programming language theory. – user17732522 Mar 12 '23 at 18:46

2 Answers2

4

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 generate type_info for 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.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
YVEF
  • 139
  • 1
  • 9
2

It doesn't have to be the destructor that is virtual, but the class needs at least one virtual function to be polymorphic.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70