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

operator+= Returns *this So Calls Chain

mediumOperator Overloading

📄 Code

Read carefully — what does this print?
1#include <iostream>
2using namespace std;
3 
4class Wallet {
5 int m_cents;
6public:
7 Wallet(int cents) : m_cents(cents) {}
8 Wallet& operator+=(int cents) {
9 m_cents += cents;
10 cout << "now " << m_cents << endl;
11 return *this;
12 }
13 int cents() const { return m_cents; }
14};
15 
16int main() {
17 Wallet w(100);
18 (w += 50) += 25;
19 cout << w.cents() << endl;
20 
21 Wallet copy = (w += 5);
22 copy += 1;
23 cout << w.cents() << " " << copy.cents() << endl;
24 return 0;
25}

🎯 Your Answer