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

Self-Assignment Guard in Action

easyOperator Overloading

📄 Code

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

🎯 Your Answer