1、为什么需要虚析构函数
如果基类析构函数不是虚析构函数,派生类的析构函数不会被调用
2、虚析构函数的作用
通过父类指针,把所有的子类对象的析构函数执行一遍
通过父类指针释放所有的子类资源
3、代码场景分析
1. #define _CRT_SECURE_NO_WARNINGS 2. #include <iostream> 3. using namespace std; 4. 5. class A 6. { 7. public: 8. A() 9. { 10. p = new char[20]; 11. strcpy(p, "obja"); 12. cout << "A" << endl; 13. } 14. virtual ~A() 15. { 16. delete[] p; 17. cout << "~A" << endl; 18. } 19. 20. private: 21. char *p; 22. }; 23. 24. class B :public A 25. { 26. public: 27. B() 28. { 29. p = new char[20]; 30. strcpy(p, "objb"); 31. cout << "B" << endl; 32. } 33. ~B() 34. { 35. delete[] p; 36. cout << "~B" << endl; 37. } 38. protected: 39. 40. private: 41. char *p; 42. }; 43. 44. class C :public B 45. { 46. public: 47. C() 48. { 49. p = new char[20]; 50. strcpy(p, "objc"); 51. cout << "C" << endl; 52. } 53. ~C() 54. { 55. delete[] p; 56. cout << "~C" << endl; 57. } 58. protected: 59. 60. private: 61. char *p; 62. }; 63. 64. void howtoDelete(A *base) 65. { 66. delete base; //不会变现出多态的属性 67. } 68. 69. int main() 70. { 71. A *p = new C(); 72. delete p; 73. 74. C *p1 = new C(); 75. howtoDelete(p1); 76. 77. 78. system("pause"); 79. } 80.
去掉virtual关键字,执行结果如下:
加上virtual关键字重新执行,结果如下: