C ++ study note _ 5: copy constructor

Source: Internet
Author: User
// Copy constructor is a special constructor. Its form parameters are referenced by objects of this class. // Purpose: use an object (the object specified by the parameter) to initialize an object of the same type that is being created. // class name // {// public: // Class Name (shape parameter); // constructor // class name (Class Name & Object Name); // copy constructor //... ///}; // Class Name: Class Name (Class Name & Object Name) // copy the constructor implementation // {function body} // If Program The compiler generates a copy constructor. // The function of executing this constructor is to initialize the corresponding data member of the object to be created by using the value of each data member of the object as the initial value. Class Point {public: Point (INT xx = 0, int YY = 0) {x = xx; y = YY;} Point (point & P ); // copy the constructor int getx () {return X;} int Gety () {return y;} PRIVATE: int X, Y;}; point :: point (point & P) {x = P. x; y = P. y; cout <"copy constructor called" <Endl ;}// (1) when an object of the class is used to initialize another object of the class, the system automatically calls it to realize Copy assignment. Int main (void) {point A (1, 2); point B (a); // The copy constructor is called cout <B. getx () <Endl; return 0;} // (2) if the function parameter is a class object, when calling the function, the real parameter is assigned to the form parameter, and the system automatically calls the copy constructor. Example: void fun1 (point P) {cout <p. getx () <Endl;} int main () {point A (1, 2); fun1 (a); // call the copy constructor return 0;} // (3) when the return value of a function is a class object, the system automatically calls the copy constructor. For example: Point fun2 () {point A (1, 2); return a; // call the copy constructor} int main () {point B; B = fun2 (); return 0 ;}

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.