[C ++ Basics] 023 _ Why Should I declare the destructor of the base class as virtual?

Source: Internet
Author: User
 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.