As i understand it is my reference SomeClass &ref=b; After that b = ref; Then c = b; SomeClass &ref2=c; then c=ref2 . But am I calling the operator = witch i have reloaded when b=ref or c = ref2 ? Something like that a.operator=(ref) ?
class SomeClass
{
public:
SomeClass()
{
a = 5;
}
SomeClass(int l_a)
{
a = l_a;
}
SomeClass& operator=(const SomeClass& l_copy)
{
this->a = l_copy.a;
return *this;
}
int a;
};
int main()
{
SomeClass a;
SomeClass b(1);
SomeClass с(6);
с = b = a;
}
2 Answers 2
By overloading the operator = in SomeClass, you are doing copy-assignment lhs = rhs (Eg : c = b, c is lhs and b is rhs). Because it returns a reference matching SomeClass& operator= expected parameter type, you can chain multiple copy-assignments such as c = b = a.
Comments
If you had:
void operator=(const SomeClass& l_copy)
{
this->a = l_copy.a;
}
Then your assignments operations would be limited to:
b = a;
c = b;
By returning the reference you can chain assignments as in:
c = b = a;
// c.operator = (b.operator = (a));
//1: b.operator= ("ref a")
//2: c.operator= ("ref b")
Comments
Explore related questions
See similar questions with these tags.
c=b=a;is the same asc=(b=a);, which is the same asc.operator=(b.operator=(a));. There is nooperator=called fora. Note that assignment has right-to-left associativity.b.operator=(a)therefore returns a reference tob, which is used as an argument forc.operator=call.SomeClass& ref = b; b = ref;case? If so, why your code does something completely different? There is norefin it. Please, edit the code to match your question.c=b=a;asb=a; SomeClass& ref=b; c=ref;as well with the same effect. There is no difference betweenc=bandc=refat the end. Still not clear what is your question, sorry.