13th read Program 2: Virtual destructor, 13th read
Problem and code:
# Include <iostream> using namespace std; class BASE {private: char c; public: BASE (char n): c (n) {} virtual ~ BASE () // virtual destructor {cout <c ;}}; class DERIVED: public BASE {private: char c; public: DERIVED (char n ): BASE (n + 1), c (n) {}// the data member of the derived class is assigned a value of n BASE class data member and is set to n + 1 ~ DERIVED () {cout <c ;}}; int main () {DERIVED d ('x'); // Through the constructor, the data member of the DERIVED class c = X, base data member c = Y return 0 ;}
Running result:
Knowledge Point summary:
The declaration of virtual destructor adds virtual
If the destructor of the base class is not defined as a virtual destructor, the pointer of the base class does not execute the destructor of the derived class. Therefore, in a better project, the fictitious functions of the base class are defined as virtual destructor.
Of course, the program given by the instructor is the object of the created derived class and does not involve pointers. Therefore, even if you remove virtual, You can execute the fictitious functions of the derived class object.