C ++ Study Notes 25, always declare the Destructor as virtual

Source: Internet
Author: User

Always remember to declare the Destructor as virtual ----> < >

Maybe you don't think this sentence is correct, but you don't need to question it.

View the following example:

# Include
 
  
# Include
  
   
Using namespace std; class B {public :~ B () {cout <"base is destroyed! "<
   
    
This is a simple example, and the output is positive.

However, let's look at the test below! <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PHByZSBjbGFzcz0 = "brush: java;"> # include # Include Using namespace std; class B {public :~ B () {cout <"base is destroyed! "<

Therefore, when a base class Pointer Points to an object in a derived class and deletes the pointer directly, the Destructor call chain will be damaged.

# Include
     
      
# Include
      
       
Using namespace std; class B {public: virtual ~ B () {cout <"base is destroyed! "<
       
        

Therefore, remember to declare the Destructor as virtual, so you never have to worry about the destruction of the Destructor call chain!


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.