snippet 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;
}
output: const copy constructor called
snippet 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;
}
output: non-const copy constructor called
snippet 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 by reference
I am so confused about:
- for snippet 2, why the non-const copy constructor here is valid? why non-const copy constructor was called, rather than the const one.
- for snippet 3, I know that copy constructor must use const reference to avoid infinite recursion. But Here class C has got
C(const C& c)
,C(C c)
won't cause infinite recursion, why it still doesn't work?
C c2=static_cast<const C>(c1);
still calls the non-const version. – Illiquid