CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List
C++ Code Walkthrough #55

Chained Assignment Runs Right to Left

hardOperator Overloading

📄 Code

Read carefully — what does this print?
1#include <iostream>
2#include <string>
3using namespace std;
4 
5class Num {
6 string m_label;
7 int m_value;
8public:
9 Num(const string& label, int value) : m_label(label), m_value(value) {}
10 Num& operator=(const Num& other) {
11 cout << m_label << " = " << other.m_label << " (" << other.m_value << ")" << endl;
12 m_value = other.m_value;
13 return *this;
14 }
15 int value() const { return m_value; }
16};
17 
18int main() {
19 Num a("a", 1), b("b", 2), c("c", 3);
20 a = b = c;
21 cout << a.value() << b.value() << c.value() << endl;
22 
23 Num x("x", 10), y("y", 20);
24 (x = y) = c;
25 cout << x.value() << endl;
26 return 0;
27}

🎯 Your Answer