大家讲道理2017-04-17 15:00:34
The main function of
析构函数
is to clean up the instance object of this class when it is no longer needed (mainly memory release.) A 基类
is also a class, and it can also have Object, so the destructor of the base class is responsible for cleaning up some memory opened within the base class.
So, for 派生类
. It may cause some memory overhead, so the derived class also needs a constructor. The base class only knows the memory overhead inside the base class, and the derived class only knows the memory overhead of the derived class itself. Among them They do not understand each other. Most inheritance relationships are based on the relationship of extending the base class.
The derived class enriches the base class. If the instance object of the derived class does not automatically call the destructor of the base class when it is destroyed, then who will do the cleanup of the base class? 基类的内部, 有一些是派生类不了解的.
For convenience, For the sake of safety and management. Therefore, when the object of the derived class is destroyed, the inheritance mechanism will call the destructor at each level hierarchically.
内存的清理工作必须严格要求. 谁开辟的,谁最后释放.
One person is responsible for the work. If a child gets into trouble, the father should not be asked to admit his mistake. At the same time, in the inheritance relationship, the base class has the responsibilities of the base class, and the derived class has the responsibilities of the derived class. The division of labor is clear, and cannot Yuezu. Only when all departments coordinate with each other can the program run smoothly.
阿神2017-04-17 15:00:34
There is no need to explicitly call the destructor of the base class in the destructor of the derived class, because there is only one destructor for each class, and the compiler knows how to choose without programmer intervention.
In addition, the execution order of destructors and constructors is also exactly the opposite:
When creating a derived class object, the execution order of constructors is the same as the inheritance order, that is, the base class constructor is executed first, and then the derived class is executed. Class constructor.
When destroying a derived class object, the execution order of the destructor is opposite to the inheritance order, that is, the derived class destructor is executed first, and then the base class destructor is executed.
巴扎黑2017-04-17 15:00:34
1. The derived class destructor will only call the base class destructor, but not the base class constructor. Your question is wrong!
2. Why is it called? A derived class consists of two parts, the base class part and the derived class part. The compiler helps us automatically call the destructor of the base class when calling the destructor of the derived class. This strategy allows us to completely ignore the base class. accomplish. Much more convenient.