Why base class destructor (virtual) is called when a derived class object is deleted?

后端 未结 7 793
再見小時候
再見小時候 2020-12-13 13:45

A difference between a destructor (of course also the constructor) and other member functions is that, if a regular member function has a body at the derived class, only the

7条回答
  •  [愿得一人]
    2020-12-13 14:17

    This is by design. The destructor on the base class must be called in order for it to release its resources. Rule of thumb is that a derived class should only clean up its own resources and leave the base class to clean up itself.

    From C++ spec:

    After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X’s direct members, the destructors for X’s direct base classes and, if X is the type of the most derived class (12.6.2), its destructor calls the destructors for X’s virtual base classes. All destructors are called as if they were referenced with a qualified name, that is, ignoring any possible virtual overriding destructors in more derived classes. Bases and members are destroyed in the reverse order of the completion of their constructor (see 12.6.2).

    Also, because there is only one destructor, there is no ambiguity as to which destructor a class must call. This is not the case for constructors, where a programmer must pick which base class constructor should be called if there isn't an accessible default constructor.

提交回复
热议问题