1

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;
}
asked Feb 18, 2020 at 8:59
12
  • 2
    c=b=a; is the same as c=(b=a);, which is the same as c.operator=(b.operator=(a));. There is no operator= called for a. Note that assignment has right-to-left associativity. b.operator=(a) therefore returns a reference to b, which is used as an argument for c.operator= call. Commented Feb 18, 2020 at 9:15
  • I have asked how objects transmit by reference when b = ref (SomeClass &ref=b) Am i use my reloaded operator = ? Commented Feb 18, 2020 at 9:31
  • What is a "reloaded" operator? Commented Feb 18, 2020 at 9:33
  • Are you asking about SomeClass& ref = b; b = ref; case? If so, why your code does something completely different? There is no ref in it. Please, edit the code to match your question. Commented Feb 18, 2020 at 9:33
  • 1
    @ZELIBOBA You can rewrite c=b=a; as b=a; SomeClass& ref=b; c=ref; as well with the same effect. There is no difference between c=b and c=ref at the end. Still not clear what is your question, sorry. Commented Feb 18, 2020 at 9:50

2 Answers 2

1

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.

answered Feb 18, 2020 at 9:27
Sign up to request clarification or add additional context in comments.

Comments

1

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")
answered Feb 18, 2020 at 9:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.