- The constructor is declared as a virtual function : The so-called virtual function is a polymorphic case only executes one, and from the concept of inheritance, always first constructs the parent class object, then can be the child class object, if the constructor is set to the virtual function, then when you constructs the parent class's constructor to display the call constructs, Another reason is to prevent the wrong, imagine if you accidentally rewrite a subclass in the same function as the parent class constructor, then your parent class constructor will be overwritten, that is, the construction of the parent class cannot be completed. It's going to go wrong.
- Call virtual function in constructor: Do not call virtual function in constructor. In the construction of a base class, a virtual function is non-virtual and does not go into a derived class, and is both a static binding used. It is obvious that when we construct an object of a subclass, we call the constructor of the base class first, construct the base class part of the subclass, the subclass is not constructed yet, it is not initialized, if you call a virtual function in the construction of the base class, it is dangerous to call an object that has not been initialized, so C + + It is not possible to invoke the virtual function implementation of a subclass when constructing the part of the parent class object. But not that you can not write the program, you write this, the compiler will not error. It's just that if you write this, the compiler will not give you the implementation of the subclass, but rather call the implementation of the base class.
- Call virtual function in destructor: Do not call virtual function in destructor. At the time of the destructor, the destructor of the subclass is called first, the subclass part of the object is reconstructed, and then the destructor of the base class is called, and if the virtual function is called in the destructor of the base class, it is very dangerous to call the function inside the sub-class object that has been destructor.
These practices are incorrect or should be avoided in C + +