Negative tive C ++ clause 7: Declares virtual destructor for a multi-state base class

Source: Internet
Author: User

Key points:

If a base class or class with polymorphism has a virtual function, the Destructor should be declared as virtual. For example

Class TimeKeeper {public: TimeKeeper ();~ TimeKeeper () ;}; class AtomicClck: public TimeKeeper // atomic clock {}; class WaterClck: public TimeKeeper // water clock {}; class WristClck: public TimeKeeper // watch {}; int main () {TimeKeeper * ptk = getTimeKeeper (); // The delete ptk object for getting the clock using the factory method; // because the Destructor declaration in the parent class is non-virtual, therefore, only the destructor of the parent class will be executed. // This will cause memory leakage of special members in the subclass}

 

The code above causes memory leakage and does not release the memory occupied by a part of the subclass. The solution is to add virtual before the destructor of the parent class, as shown below:

class TimeKeeper{public:       TimeKeeper();       virtual ~TimeKeeper();};

 

Key points: class memory

(1) Internal member variables:

  • Common variables: Memory usage, but the alignment principle should be noted (similar to struct type ).
  • Static modified static variables: NO content is occupied because the compiler places it in the global variable area.
(2) Internal member functions:
  • Common functions: Does not occupy memory.
  • Virtual Functions: Takes 4 bytes to specify the entry address of the virtual function table of the virtual function. Therefore, the addresses occupied by the virtual functions of a class are unchanged, and there is no relationship with the number of virtual functions.

PS: even if there is nothing in the class, it must take up one byte.

 

 

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.