On Dec 16, 9:06 am, siddhu <siddharth....@gmail.comwrote:
If there is reference member variable in the class, why doesn't
default assignment operator work?
class A
{
int& i;
public:
A( int& ii):i(ii){}
//A& operator=(const A& a){i = a.i;}
};
int main()
{
int k =10;
A a(k);
A b(k);
a = b; //This does not compile
}
But if I uncomment my assignment operator it works. I hope default
assignment operator works the same way.
References are non-copyable/non-assignable. Your assignment operator
works because you are not actually assigning one reference to another
reference. The reference member 'i' in your case keeps referring to
the same variable that it referred to when the object was constructed
i.e. 'k'. And you are just assigning the value to it. As a result the
value of 'k' will change upon assignment a=b;. You can verify using
two different variables (having different initial values) to construct
A objects a and b.
I don't know what does the compiler generated assignment operator do,
but it might just be giving the error seeing a (non-assignable)
reference member. I am not sure how one would write a statement in C++
which would do assignment of references because anything like this:
reference_1 = reference_2;
would not actually be assigning a reference to a reference but
assigning variable referred to by reference_1 by value of variable
referred to by reference_2.