Do you need a Virtual destructor?
Class Wizard using VC automatically generates a class, gets two empty functions: constructor and virtual destructor. Why is the destructor to declare a Virtual?
If a class is to be used in Polymorphic, then this virtual is required. such as:
#include
Class animal {char * ap; public: animal () {ap = new char; std :: cout << "Animal ctor" << std :: endl;} virtual void foo () {std :: cout << "Animal :: foo "<< std :: endl;} Virtual ~ Animal () {std :: cout <<" animal dtor "<< std :: end1; delete ap;}}
Class dog: public animal {char * dp; public: dog () {dp = new char; std :: couid "<< std :: endl;} virtual void foo () {std :: cout < <"Dog :: foo" << std :: endl;} Virtual ~ Dog () {delete dp; std :: cout << "DOG DTOR" << std :: endl;}};
INT main () {animal * pa = new dog (); PA-> foo (); delete pa; return 0;}
Delete PA is actually equivalent to: PA-> ~ Animal (); release the memory pointed to by PA (perhaps Free (Pa)). Here, because ~ Animal () is Virtual, although it is called by the animal type, according to the information of V-TABLE, ~ DOG () is called correctly. If the Virtual property is removed, the called ~ Animal (), the constructor of the Dog class is called and the destructor is not called, and the resource allocated in the constructor is not released, resulting in memory leakage. The default statement of the designer is Virtual to avoid this problem.
Another problem is that sometimes Virtual is not required. If a class will not be inherited, such as a UTILITY class, this class is completely static; or some classes may be inherited, but will not be used, that is, in addition to the destructor, there is no other method It is Virtual, then you can remove the virtual property.
After the Virtual property of the restructure function is removed, because there is no other Virtual function in this class, V-TABLE does not generate when compiled, which saves compilation time and reduces the size of the final generated program. More importantly, comply with this rule, given the maintainer of the class, that is, the class should not be used as a polymorphism class.
Similarly, as an abstraction, if you imitate the Java's Interface, declare the following virtual base class:
Class AbstractBase {Virtual Method1 () = 0; Virtual method2 () = 0;}; then add an empty Virtual destructor: virtual ~ AbstractBase () {}
If you are familiar with COM, you may notice that this Virutal constructor is not in Com Interface. This is because COM maintains objects by using a reference counting mechanism. When you use a COM object, call Release (), the internal implementation of the COM is not zero. If so, call delete this; because Release () is Virtual, the correct derived class corresponding to the COM object is called. Delete this will call the correct destructor to achieve the effect of using the Virtual destructor.