C ++ review notes-copy constructor and assign value Constructor

Source: Internet
Author: User

1. Copy the constructor form
For Class X, if its function form is as follows:
A) X &
B) const X &
C) volatile X &
D) const volatile X &
If no other parameters or other parameters have default values, this function is a copy constructor.
X: X (const X &); is a copy constructor.
X: X (const X &, int val = 10); is a copy constructor.
 
2. There can be more than one copy constructor in a class
Class X {
Public:
X (const X &);
X (X &); // OK
};
The compiler calls the const copy constructor or non-const copy constructor according to the actual situation.
 
3. Default copy constructor Behavior
A) call the copy constructor of the parent class first.
B) if the data member is an instance of a class, the copy constructor of the class is called.
C. copy other members by bit
 
4. Default Value assignment constructor Behavior
A) call the value assignment constructor of the parent class first.
B) if the data member is an instance of a class, the value assignment constructor of the class is called.
C) Other members copy www.2cto.com by bit
 
5. Provides the displayed copy and value assignment constructors.
The basic principle is that the subclass must call the corresponding functions of the parent class. For more information, see
Derive (const Derive & obj): Base (obj)
{
......
}
 
Derive & operator = (const Derive & obj)
{
If (this = & obj)
Return * this;
 
// Method 1
Base: operator = (obj );
 
// Method 2
Static_cast <Base &> (* this) = obj;
Return * this;
}

In addition, when your member variables have const or references, the system cannot provide you with default copy and assign value constructors. We must handle these special situations by ourselves.

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.