C ++ assignment function and copy constructor

Source: Internet
Author: User

When we see the "=" operator, we think it is necessary to call the value assignment function. However, in the following example, Statement a B = c shows that the copy constructor is called.

Conclusion: when the "=" operator is assigned a value to an object, if it appears during object definition, the copy constructor is called. If it is not, B = d In the example, the value assignment function.

 

# Include <iostream>
Using namespace std;

Class
{
Public:
A (int d ):
Data (d)
{};
A (const a & aa );
A & operator = (const a & aa );
Void show ();
Private:
Int data;
};
A: a (const a & aa)
{
Cout <"copy constructor" <endl;
Data = aa. data;
// Return * this;
};
A & a: operator = (const a & aa)
{
Cout <"assignment" <endl;
If (this = & aa)
Return * this;
Data = aa. data;
Return * this;
};
Int main ()
{
A c (1 );
A d (2 );
A B = c; // value assignment function? Or copy the constructor?
B = d;
Return 0;
}

 

Running result

[Root @ localhost tmpc ++] #./s1
Copy constructor
Assignment

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.