Copy Constructor (c + + frequently asked question one)

Source: Internet
Author: User

* What is copy constructor and can be called copy constructor (shallow copy and deep copy)

The following code shows what a copy constructor is, and if you do not manually define a copy constructor, the system assigns you a shallow copy of the copy constructor by default.

Class cat{public://Constructor Cat (): M_pmyname (NULL), m_unage (0) {cout<< "Cat Defult ctor" <<ENDL;} Copy constructor (copy constructor) Cat (const cat& Other) {this->m_unage = other.m_unage;//release its own space first if (0! = this->m_pmyname) { Delete this->m_pmyname;this->m_pmyname = NULL;} If the target has a name if (other.m_pmyname) {///dynamically assigns a name to a heap of length +1: Here is the deep copy int len = strlen (other.m_pmyname); m_pmyname = new Char[len + 1];memset (m_pmyname, 0, len+1); memcpy (M_pmyname, oth Er.m_pmyname, len+1);} /*//if the target has a name if (other.m_pmyname) {///dynamically assigns a name to the length of +1 of the heap: Here is a shallow copy. The pointer is copied only, not the object pointed to by the pointer m_pmyname = Other.m_pmyname;}  */} unsigned int m_unage; char* m_pmyname;  } Practical application ... void Main () {    cat A;    Cat B (A);//construct object B, use copy constructor to construct    cat C = A;//Note object initialization here to invoke copy constructor, not assignment}

Copy Constructor (c + + frequently asked question one)

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.