1. As the polymorphic base class should declare a mass virtual destructor. Assume that the class has a virtual destructor, regardless of the virtual destructor.
2.classed is designed to assume that a virtual destructor should not be declared if it is not used as a base classed, or not for polymorphism.
#include <iostream>using namespace Std;class a{ private: int i; Public: virtual void Display () { cout<<i<<endl;} Virtual ~a () {}; ~a (); A (): I (0) {}};class b:public a{ Private: int J; Public: void Display () { cout<<j<<endl;} B (): J (1) {} ~b () {}};iint main () { A *ptr = new B (); Ptr->display (); Delete ptr; return 0;}
When a class A destructor is not defined as a non-virtual destructor, the compilation will give an error, such as the following
It can be executed normally when defined as a virtual destructor.
watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvbml6agfubml6agfu/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ Dissolve/70/gravity/center ">
The problem is that PTR points to a subclass (class B) object, which is deleted by a base class (Class A) pointer, and the base class has a non-virtual destructor.
The subclass component of the run-time object (that is, member variable J, declared in Class B) is not destroyed, and the destructor of the subclass fails to run. However, the base class component is usually destroyed, resulting in a bizarre "partial destruction" object. A resource leak has been created.
No matter what class is only with the virtual function it is almost certain that there should also be a virtual destructor.
Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.
Effective C + + clause 7