Effective C + + clause 07: Declaring a virtual destructor for a polymorphic base class

Source: Internet
Author: User

Remember:
A base class with polymorphic properties should declare a virtual destructor. If class has any virtual functions, it should have a virtual destructor.
The design purpose of class is not to declare a virtual destructor if it is not used as a base class, or if it is not for polymorphism.

class timekeeper {public:    timekeeper ();     ~timekeeper ();    ...}; class  Public timekeeper {...}; class  Public timekeeper {...}; Timekeeper// Get an object pointer to derived class  ... delete ptk;  // because timekeeper with a non-virtual destructor, the destructor of the derived class is not called, resulting in a resource leak. 

To solve this problem, we need only

class timekeeper {public:    timekeeper ();     virtual ~timekeeper ();    ...};


The purpose of the virtual function is to allow the implementation of the derived class to be customized. Any class with the virtual function is almost certain that there should be a virtual destructor as well.
If class does not contain a virtual function, it usually means that it is not used as a base class, so its destructor does not need to be virtual.

With the pure virtual destructor, you must provide a definition for this pure virtual destructor.

class Amov {public:    virtual0;}; Amov::~amov () {}














Effective C + + clause 07: Declaring a virtual destructor for a polymorphic base class

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.