* 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)