After studying the member copying and the assignment operator in C++,
and looking at ” member copying of class ” which explains the conditions where default assignment operator cannot be generated. I am not very clear about the concepts as the following example I tried actually works on g++4.5
#include<iostream>
using namespace std;
class Y{
int& x;
const int cx;
public:
Y(int v1,int v2)
:x(v1),cx(v2)
{}
int getx(){return x;}
int getcx(){return cx;}
};
int main()
{
int a = 10;
Y y1(a,a);
Y y2 = y1;//assignment
cout<<y1.getx()<<" "<<y1.getcx();
return 0;
}
So where am I not getting the concepts. Please suggest other examples (if possible) so that I can understand better.
Y y2 = y1;is not an assignment. It’s a copy constructor call. If you declare and initialize a variable on the same line, a one parameter constructor is called with the right hand side of the equals sign as the parameter. There’s nothing aboutYthat prevents the default copy constructor from being instantiated (and called).Try the following:
This should fail, although I can’t test it right now.