Why should the destructor of base classes be virtual?

前端 未结 5 1162
长情又很酷
长情又很酷 2021-02-05 19:14

in C++: Why should the destructor of base classes be virtual?

5条回答
  •  孤独总比滥情好
    2021-02-05 19:42

    You want them to be virtual so that all subclass destructors are automatically called when the object is destroyed, even if it is destroyed through a pointer to the base class. In the following code:

    class base {
    public:
      virtual ~base() { }
    };
    
    class derived : public base {
    public:
      ~derived() { }  // Inherits the virtual designation
    };
    
    int main(void)
    {
      base *b = new derived;
    
      delete b;
    }
    

    The derived destructor will only be called if the base destructor is virtual.

    As Magnus indicates, you don't have to do this if you aren't taking advantage of polymorphism. However, I try to develop the habit of declaring all my destructors virtual. It protects me against the case where I should have declared them virtual but forget to do so. As Johannes indicates, this habit can impose a small space and performance penalty when the virtual designation is not needed.

提交回复
热议问题