Why is the destructor of the parent class declared as virtual in C ++?

Source: Internet
Author: User
# Include <iostream> using namespace STD; class base {public: Base () {} virtual ~ Base () {} // The destructor of the base class should be declared as a virtual destructor. Virtual void test () {cout <"base test" <Endl ;}}; class derived: public base {public: derived (){}~ Derived () {cout <"delete derived" <endendl;} void test () {cout <"derived test" <Endl ;}}; void main () {base * pbase = new derived (); // the pointer of the parent class points to the object of the derived class. Pbase-> test (); Delete pbase ;//If the Destructor without the base class is not declared as virtual, The destructor of the subclass will not be executed.// Declare the destructor of the parent class as a virtual function. The function is to use the pointer of the parent class to delete a derived class object .}

Declare the destructor of the parent class as virtual to call the destructor of the subclass When deleting the parent class pointer.

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.