fragment 1:
#include<iostream>
using namespace std;
class C{
public:
C(){}
C(const C& c){
cout<<"const copy constructor called"<<endl;
}
};
int main(){
C c1;
C c2 = c1;
return 0;
}
conclusion : constructor const const called
fragment 2:
#include<iostream>
using namespace std;
class C{
public:
C(){}
C(const C& c){
cout<<"const copy constructor called"<<endl;
}
C(C& c){
cout<<"non-const copy constructor called.\t "<<endl;
}
};
int main(){
C c1;
C c2 = c1;
return 0;
}
conclusion : a non-content copy constructor called
fragment 3:
#include<iostream>
using namespace std;
class C{
public:
C(){}
C(const C& c){
cout<<"const copy constructor called"<<endl;
}
C(C c){
cout<<"non-const copy constructor called.\t "<<endl;
}
};
int main(){
C c1;
C c2 = c1;
return 0;
}
output : error: copy constructor must pass its first argument with a reference
I'm so confused:
- for fragment 2, why is the non-content copy constructor valid here? why the constructor of a non-composite copy was called, and not a constant one.
- for fragment 3, I know that the copy constructor should use a const reference to avoid infinite recursion. But here the class C has
C(const C& c), C(C c)will not cause infinite recursion, why is it still not working?