[014] Precautions for using destructor as virtual functions

Source: Internet
Author: User

1. When a destructor is a virtual function, the destructor of all its derived classes automatically become virtual functions (whether or not they are marked as virtual ).

2. when the destructor of the base class is a virtual function, if you call the destructor of the subclass, the program will first call the destructor of the derived class, then, call the destructor of the base class.

However, if the destructor of the base class is not a virtual function, only the destructor of the base class will be called.

Example:

Class base {virtual ~ Base () {};...}; Class Device: public base {~ Device () {};}; base * pb = new device; Delete Pb;

The program first calls the device destructor and then calls the base destructor.

If the virtual of the base is removed, only the destructor of the Base will be called.

● However, if the derived class type is used to point to the derived class, the device destructor will be called first, regardless of whether the base class has virtual or not, and then the base destructor will be called. Example:

Class base {~ Base () {};...}; Class Device: public base {~ Device () {};}; device * Pd = new device; Delete PD;

 

[014] Precautions for using destructor as virtual functions

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.