copy constructor
In C++, a function with the same name as the class name and whose formal parameters are reference types of objects of this class is called a copy constructor . Like the constructor, the system will automatically generate one when we do not actively define it. , perform corresponding simple assignments between two object members, used to initialize an object, such as the following situation:
#include<iostream>usingnamespacestd;#definePI3.1415classCircle{private:doubleR;public:Circle(doubleR);Circle(Circle&A);doublearea();doublegirth();};Circle::Circle(doubleR){cout<<Constructor <<endl;this->R=R;}Circle::Circle(Circle&A){cout<<CopyConstructor<<endl;this->R=AR;}doubleCircle::area(){returnPI*R*R;} doubleCircle::girth(){return2*PI*R;}intmain(){CircleA(5);CircleB(A);return0;}
In this example, a Circle class is defined, and a constructor with parameters and a copy constructor are defined respectively. Then the A object is defined in the main function, the initial value is passed in, and the constructor with parameters is called. And define the B object, and initialize the B object through the A object. The running results are as follows:
The A object defined for the first time calls the constructor with parameters, and the second B object is initialized through the A object, so the copy constructor is called.
Please also try it on your computer.
You may have questions. At the beginning we mentioned that if we don't actively define a copy constructor, one will be automatically generated for us, so why do we have to define it ourselves? That's because the default copy constructor only performs simple assignments. In some cases, problems may occur. This involves deep copy and shallow copy . We will introduce it to you in detail in the next section!