1 #include <iostream> 2 using namespace std; 3 4 class Father{ 5 6 public: 7 ~Father(){ 8 cout<<"Father's Desconstruct Called."<<endl; 9 }10 };11 12 class Son : public Father{13 public:14 ~Son(){15 cout<<"Son's Desconstruct Called."<<endl;16 }17 };18 19 int main(){20 21 Father *f = new Son();22 delete f;23 24 system("pause");25 26 return 0;27 }
In the above Code, the parent class pointer is used to point to new and other objects. This is no problem. Then, the parent class pointer variable is deleted. What is the output above?
Father's Desconstruct Called.
It can be seen that the destructor of the subclass is not called. If the subclass has a new memory, the memory will be lost. How can we ensure that when the parent class pointer is deleted, the destructor of the subclass is also called? See the following code:
1 #include <iostream> 2 using namespace std; 3 4 class Father{ 5 6 public: 7 virtual ~Father(){ 8 cout<<"Father's Desconstruct Called."<<endl; 9 }10 };11 12 class Son : public Father{13 public:14 ~Son(){15 cout<<"Son's Desconstruct Called."<<endl;16 }17 };18 19 int main(){20 21 Father *f = new Son();22 delete f;23 24 system("pause");25 26 return 0;27 }
What is output?
Son's Desconstruct Called.Father's Desconstruct Called.
This is the destructor of dynamic concatenation. As to why the sub-class destructor can be called, another concept is involved: virtual function table. See http://blog.csdn.net/hairetz/article/details/4137000 for details