Why C + + sets a destructor for a base class as a virtual function

Source: Internet
Author: User

The sequence of destructor calls for objects is from derived classes to base classes

So what if the base class pointer points to the object of the derived class and performs the destructor correctly?


Let's look at a declaration of a class

Class Subject{public:~subject (); Subject ();}; Class Concretesubject:public Subject{public:concretesubject (); ~concretesubject ();};

Creates a pointer to the base class and deletes the object

Subject * con = new ConcreteSubject ();d elete con;

The result shows that only the destructor of the base class is called ~subject ()

The destructor for the derived class, ~concretesubject (), is not called


If not, the destructor for the base class is set to a virtual function

Then the destructor of the pointed object is not invoked dynamically at execution time

That's the polymorphic nature.

A series of memory problems occur when the object is not properly disposed at run time



Why C + + sets a destructor for a base class as a virtual function

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.