In addition to the constructor that is automatically called when a class object is created as mentioned in the previous section, a function is also automatically called when the object is destroyed. It also has the same name as the class name and has no return value. There is a tilde ~ in front of the name. Use To distinguish the constructor, its function is mainly used to clean up the aftermath after the object is released. It is the destructor .
The same as the constructor and the class name, there is no return value. If the user does not define it, the system will automatically generate an empty destructor. Once defined by the user, it is automatically called when the object is destroyed.
Unlike constructors, although they are both public types. Construction can be overloaded and has multiple brothers, but destructor cannot be overloaded, but it can be a virtual function, and a class can only have one destructor.
Next, we take the Student class as an example and continue to add a destructor. At the same time, we add information about the current class in both the constructor and the destructor to identify which class is created and destroyed. Please read the code carefully:
#include<iostream>#include<Cstring>usingnamespacestd;classStudent{private:intnum;//student number charname[100];//name intscore;//score public:Student(intn,char*str,ints);~Student ();intprint();intSet(intn,char*str,ints);};Student::Student(intn,char*str,ints){num=n;strcpy(name,str);score=s;cout <<num<<<<name<<<<score<<;cout<<Constructor<<endl;}Student::~Student(){cout<<num<<<<name<<<<score<<; cout<<destructor<<endl;}intStudent::print(){cout<<num<<<<name<<<<score<<endl;return0;}intStudent::Set(intn,char*str,ints) {num=n;strcpy(name,str);score=s;}intmain(){StudentA(100,dot,11);StudentB(101,cpp,12);return0;}
Please carefully understand the constructor and destructor in the above code, and note that two objects A and B are defined in the main function, and test it on your own computer. You can see that the running effect is as follows:
You can see that the order of calling the constructors and the order of calling the destructors of objects A and B is completely opposite! The reason is that objects A and B are both local objects and are also stored in the stack area. They also follow the "first in, last out" order!
Please be sure to test and verify the results in person!