why should the parameter in copy construction be a reference

时间:2023-03-09 23:45:34
why should  the parameter in copy construction be  a reference

if not, it will lead to an endless loop!!!

 # include<iostream>
using namespace std;
class A
{
public:
int var; A():var(){} A(A &a){this->var = a.var;cout << "copy\n";} void operator=(A b){cout << "assign\n";} A func(A a){return a;}
//A func(A &a){ return a; } ~A(){cout << "destroy\n";}
}; int main()
{
A a, b, c;
b.var = ;
a = b;
cout << "\n";
c = a.func(b);
system("pause");
}

update:  1) class a = b; 2) a=c;

1) will call copy constructor, because a havent be constructed;

2) will call assignemnt constructor, because a has it's mem room, we should just modify it's value