C + + Class four default function-constructor constructor copy constructor assignment constructor

Source: Internet
Author: User

Each class has only one destructor and one assignment function, but it can have multiple constructors (one copy constructor, others called ordinary constructors). For any class A, if you do not write the above functions, the C + + compiler will automatically generate four default functions for a, for example:

A (void);//Default parameterless constructor

A (const a&a);//Default copy constructor

~a ();//Default destructor

a&operator= (const A &a);//Default assignment constructor

1), "Default copy Constructor" and "Default Assignment function" are all implemented by "bit copy" rather than "value copy", and if the class contains pointer variables, these two functions are doomed to error.

2), when the class has not been generated, the call is a copy constructor, when the class has been generated, the call is an assignment constructor, as follows:

A;

A b;

  b = a;//The Class A and B are now generated, so the assignment constructor is called

A C;

A d=c;//when Class D is not yet generated, the copy constructor is called

3), all function calls are arguments, the copy constructor is called. If a function argument uses a reference type, no copy of the argument will occur, and no function will be called.

As follows:

void Print_a (const a A);//Call copy constructor

void Print_b (const A &a);//For reference, no function is called

4), copy constructors and assignment constructors to implement.

A::A (const A&A)

{

}

The copy constructor is not returned as a completely new class.

A &a::operator= (const a&a)

{

return *this;

}

The assignment constructor returns itself, *this, as a large operation on the original class.

C + + Class four default function-constructor constructor copy constructor assignment constructor

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.