1. Virtual functions should not be called in constructors and destructors
The polymorphism of virtual function is realized by virtual table and virtual pointer. Virtual tables and virtual pointers are refined and established on a per-layer basis when the base class and derived classes are initialized. Each object has its own virtual table and virtual pointer. Therefore, virtual tables and virtual pointers in the base class constructors are imperfect, and calling virtual functions can produce unexpected results.
The virtual function implements the late binding, destructors are destroyed from the outermost (late derivation) to the innermost (early derivation), and if a virtual mechanism is used in the destructor, it is possible to bind to a hierarchy that is later derived from a derived hierarchy that needs to be refactored, and this level, which has been refactored out, will cause an exception. so the C + + compiler ignores the virtual mechanism used in destructors.
2. The initialization list of constructors is preferably a complete list of member variables, and class type member variables are best placed in the initialization list.
The order of initialization of member variables is related to the order of declarations, regardless of the sequence of initialization lists. The member variables of the built-in type are consistent in the initialization list and the efficiency of initialization in the constructor body. A member variable of a class type is initialized in the initialization list, which is the true initialization, and is only assigned in the constructor body. If you assign a value to a member variable of a class type in the constructor body, the constructor first calls the default constructor of the class type when the initialization list is executed, and then assigns the value again in the constructor body.
3. If a class has a derived class, the destructor is best for a virtual function, otherwise the destructor for the subclass will not be called when the parent class pointer (actually points to the subclass object) is refactored.
4. Use the parent pointer to release the subclass object array.
Because the array is offset by the size of the actual type. If you use a parent pointer to release a subclass object array, the array is considered to be a parent class type Object array, which produces an error when the second element is disposed because the offset is not correct.
The attention points of constructors and destructors