A brief introduction to the destructor of derived classes in C + + programming _c language

Source: Internet
Author: User

Like constructors, destructors cannot be inherited.

When you create a derived class object, the constructor's invocation order is the same as the inheritance order, the base class constructor is executed, and then the constructor of the derived class is executed. For destructors, however, the invocation order is reversed, that is, the destructor of the derived class is executed first, and then the destructor of the base class is executed.

Take a look at the following example:

#include <iostream>
using namespace std;
Class a{public
:
 A () {cout<< "a constructor" <<ENDL;}
 ~a () {cout<< "A destructor" <<ENDL;}
;
Class B:public a{public
:
 B () {cout<< "B constructor" <<endl;}
 ~b () {cout<< "B destructor" <<ENDL;}
;
Class C:public b{public
:
 C () {cout<< "C constructor" <<endl;}
 ~c () {cout<< "C destructor" <<ENDL;}
;
int main () {
 C test;
 return 0;
}

Run Result:

A constructor
b constructor
c constructor
C destructor
b destructor
a destructor

From the results of the run, it is clear that the execution order of constructors and destructors is reversed.

It should be noted that a class can have only one destructor, which does not have two semantics when invoked, so the destructor does not need to be called explicitly.

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.