"C + +" a pen question about inheritance and destruction

Source: Internet
Author: User

The topic is as follows, to output the result

    classA { Public: A () {cout<<"A"<<Endl; }         ~a () {cout<<"~a"<<Endl;          }     }; classB: PublicA { Public: B (A&a): _a (a) {cout<<"B"<<Endl; }         ~B () {cout<<"~b"<<Endl; }     Private: A _a;          }; intMainvoid) {A A;        b b (a); return 0; } 

Here's the answer first:

[root]$./classAAB~B~a~a~a

You might find it strange, why not tune the constructor of a a once. In fact, this is due to the use of the initialization list, the initialization list in the initialization of the object of the class, the use of the copy constructor.

Modify the code to increase the printing of the copy constructor.

    classA { Public: A () {cout<<"A"<<Endl; }         ~a () {cout<<"~a"<<Endl; } A (Consta& a) {cout <<"Copy"<<Endl;}          }; classB: PublicA { Public: B (A&a): _a (a) {cout<<"B"<<Endl; }         ~B () {cout<<"~b"<<Endl; }     Private: A _a;          }; intMainvoid) {A A;        b b (a); return 0; }   

Then look at the results of the operation, so that the number of construction and destruction is consistent.

[root]$./classaacopyb~B~a~a~a

"C + +" a pen question about inheritance and destruction

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.