concept
- There is only one parameter, which is a reference to the same object
X::X(X&)
OrX::X(const X&)
often quoted more often- The system will generate a default copy constructor to complete the shallow copy function
- If you define your own copy constructor, the default one will be useless
Three situations that work
- When using an object to initialize another object,
classname object1(object2)
classname object1 = object2
this is an initialization statement, not an assignment- The parameter is an object of class A. When invoking, the copy constructor of class A will be called
void func(A a1)
, and all class objects must be initialized. This initialization will call the copy constructor function (the overhead will be relatively large, so generally consider constant reference parameters )- The return value is an object of class A, and the copy constructor is called upon return.
WAITING
- Assignment between objects does not result in a copy constructor call (if it is not initialized or assigned)
Example
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
class student
{
private:
string name;
char* hobby;
int age;
public:
student(string n="no",char h[]=nullptr,int a=0);
student(const student& s);
~student();
void displace();
} ;
student::student(string n,char h[],int a):name(n),age(a)
{
hobby = new char[strlen(h)+1];
strcpy(hobby,h);
}
student::student(const student& s):name(s.name),age(s.age)
{
hobby = new char[strlen(s.hobby)+1];
strcpy(hobby,s.hobby);
}
student::~student()
{
delete [] hobby;
}
void student::displace()
{
cout<<name<<" is "<<age<<" years old and good at "
<<hobby<<endl;
}
int main()
{
student s2("Jeff","studying",20),s3("Alice","talking",18)
,s1=s2;
s2.displace();
s3.displace();
cout<<"S1 as followed: "<<endl;
s1.displace();
}
ps. If there is a dynamic allocation of memory, it must be the destructor delete