Display the call constructor and destructor

Source: Internet
Author: User

I went to HP for an interview two days ago and asked if the constructor and destructor can be displayed and called.

When I got back to the Internet and checked it, both of them can be displayed and called. As follows:

Class

{

Public:

A ()

{

Cout <"A cnostructor" <Endl;

}

~ A ()

{

Cout <"A destructor" <Endl;

}

};

 

Void main ()

{

A;

A. A: A (); // display the call constructor. If it is written as a. A (), an error is returned.

A .~ A (); // display that the Destructor is called, but object A is not destroyed at this time.

}

The output result is as follows:

A constructor

A constructor // displays the result of calling the constructor.

A destrucotr // displays the result of calling the destructor. At this time, the object is not destroyed.

A destructor // The Destructor is automatically called when the object is destroyed.

 

Conclusion: It is shown that calling constructor and destructor is the same as calling a common function, and does not mean creating or destroying objects. However, if the constructor dynamically allocates space, it is displayed that memory leakage occurs when calling the constructor. If the constructor releases the dynamically allocated space, the unified memory is released multiple times, and a serious error occurs.

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.