C + + Learning (24)

Source: Internet
Author: User

1 //Study of Virtual destructor function2 //If an external program uses the new operator to define a dynamic object, the delete operator is used to delete the dynamic object when the external program ends.3 //However, if the external program takes advantage of the assignment compatibility principle, assigns the address of the derived class object of the dynamic request to the base class object pointer, because the delete operator implies the automatic invocation of the destructor4 //so at this point the system automatically calls the destructor of the base class, which can cause a memory leak problem5 //The following is an example of a virtual destructor6#include <iostream.h>7#include <string.h>8 9 classa{Ten      Public: One A () {} A //~a () { - //cout<< "base class destructor" <<endl; - //        } the  -         Virtual~A () { -cout<<"base class destructor"<<Endl; -         } +  - }; +  A classAa: Publica{ at     Private: -         Char*AA; -         intlength; -      Public: -AA (Char*message) { -Length=strlen (message) +1; inAa=New Char[length]; - strcpy (aa,message); to         } +~AA () { -             DeleteAA; thecout<<"derived class destructor"<<Endl; *         } $ Panax Notoginseng }; -  the intMain () { +A *pa=NewAA ("Hello"); A     DeletePA; the     return 0; + } -  $ //illustrated by This example $ //whenever a useful operator in a constructor of a derived class or other member function of a derived class new dynamically requests memory space, the destructor of its base class must be designed as a virtual destructor

C + + Learning (24)

Related Article

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.