fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int count = 0;
  5.  
  6. class Sample {
  7. int *p;
  8. int q;
  9. int m_count;
  10.  
  11. public:
  12. Sample() {
  13. m_count = count;
  14. cout<<"Constructor called for m_count = "<< count++ << endl;
  15.  
  16. p = new int;
  17. q = 0;
  18. }
  19.  
  20. Sample& operator =(const Sample &rhs) {
  21. cout<<"Assignment Operator (m_count " << m_count << " = m_count " << rhs.m_count << ") " <<endl;
  22. if(this != &rhs)
  23. {
  24. delete p; // Unnecessary
  25. p = new int; // Unnecessary
  26. *p = *(rhs.p);
  27. }
  28. return *this;
  29. }
  30. };
  31.  
  32. int main() {
  33. Sample a;
  34. Sample b;
  35. Sample c;
  36.  
  37. a = (b = c); // (b = c) will return a Sample&
  38. }
Success #stdin #stdout 0s 3428KB
stdin
Standard input is empty
stdout
Constructor called for m_count = 0
Constructor called for m_count = 1
Constructor called for m_count = 2
Assignment Operator (m_count 1 = m_count 2) 
Assignment Operator (m_count 0 = m_count 1)