When C + + destructors need to be declared as virtual functions

Source: Internet
Author: User

And look at the example below

Class Deriver:public Base
{

...;

};

Base *PB = new Deriver;
Delete PB; When the child class contains a resource that needs to be freed,
If the virtual ~base () is not declared, a memory leak can occur.


In code design, if a derived class has its own space for application in heap, and it uses a derived class to convert to a base class, be sure to declare a virtual destructor. If you do not meet both of these conditions, do not declare a virtual destructor (declaring a virtual destructor and declaring a virtual member function will occupy a virtual pointer).

In the process of code design, it is best to explicitly declare both the base class and the derived class destructor as virtual functions.

Make sure that when you use a base class pointer that points to a derived class object to release the memory space of a derived class object,
The destructor of a derived class can be called normally.

It's called polymorphism.

If you point to a derived class object with a pointer to a base class. When you delete this object, only the destructor of the base class is executed and the derived class does not perform the destructor. The destructor of a derived class is performed only when the destructor of the base class is set to a virtual function.
If you need to delete objects from the base class, the destructor of the object needs to be virtual

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.