Why are destructors not virtual by default?

来源:互联网 发布:通达信布林线公式源码 编辑:程序博客网 时间:2024/05/20 17:24
Because many classes are not designed to be used as base classes. Virtual functions make sense only in classes meant to act as interfaces to objects of derived classes (typically allocated on a heap and accessed through pointers or references).

So when should I declare a destructor virtual?Whenever the class has at least one virtual function. Having virtual functions indicate that a class is meant to act as an interface to derived classes, and when it is, an object of a derived class may be destroyed through a pointer to the base. For example:

class Base {// ...virtual ~Base();};class Derived : public Base {// ...~Derived();};void f(){Base* p = new Derived;delete p;// virtual destructor used to ensure that ~Derived is called}

Had Base's destructor not been virtual, Derived's destructor would not have been called - with likely bad effects, such as resources owned by Derived not being freed.

原创粉丝点击