← Back to Question List
C++ Code Walkthrough #54
Self-Assignment Guard in Action
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <string>3using namespace std;45class 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};1920int 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}